junit4测试学习

JUnit 4 使用 Java 5 中的注解(annotation),如下是JUnit 4 经常使用的几个 annotation 介绍单元测试

@Before:初始化方法测试

@After:释放资源spa

@Test:测试方法,在这里能够测试指望异常和超时时间资源

@Ignore:忽略的测试方法it

@BeforeClass:针对全部测试,只执行一次,且必须为static voidio

@AfterClass:针对全部测试,只执行一次,且必须为static voidclass

一个JUnit 4 的单元测试用例执行顺序为:test

@BeforeClass –> @Before –> @Test –> @After –> @AfterClassimport

每个测试方法的调用顺序为:方法

@Before –> @Test –> @After

写个例子测试一下,测试一下

import static org.junit.Assert.*; 

import org.junit.After;

import org.junit.AfterClass;

import org.junit.Before;

import org.junit.BeforeClass;

import org.junit.Ignore;

import org.junit.Test; 

public class JUnit4Test {

@Before

public void before() {

  System.out.println("@Before");

}

@Test

public void test() {

  System.out.println("@Test");

  assertEquals(5 + 5, 10);

}


@Ignore

@Test

public void testIgnore() {

  System.out.println("@Ignore");

}


@Test(timeout = 50)

public void testTimeout() {

  System.out.println("@Test(timeout = 50)");

  assertEquals(5 + 5, 10);

}


@Test(expected = ArithmeticException.class)

public void testExpected() {

  System.out.println("@Test(expected = Exception.class)");

  throw new ArithmeticException();

}


@After

public void after() {

   System.out.println("@After");

  }

  

  @BeforeClass

  public static void beforeClass() {

   System.out.println("@BeforeClass");

  };

  

  @AfterClass

  public static void afterClass() {

   System.out.println("@AfterClass");

  };

};

输出结果

@BeforeClass

@Before

@Test(timeout = 50)

@After

@Before

@Test(expected = Exception.class)

@After

@Before

@Test

@After

@AfterClass

 

@BeforeClass and @AfterClass                     @Before and @After

在一个类中只能够出现一次                                  在一个类中能够出现屡次,便可以在多个方法的声明前加上这两个                                                                                          Annotaion标签,执行顺序不肯定

方法名不作限制                                                   方法名不作限制

在类中只运行一次                                                在每一个测试方法以前或者以后都会运行一次

@BeforeClass父类中标识了该Annotation的        @Before父类中标识了该Annotation的方法将会先于当前类中标识了该

方法将会先于当前类中标识了该Annotation的       Annotation的方法执行。

方法执行。

@AfterClass 父类中标识了该Annotation的          @After父类中标识了该Annotation的方法将会在当前类中标识了该

方法将会在当前类中标识了该Annotation的           Annotation的方法以后执行

方法以后执行

必须声明为public static                                        必须声明为public 而且非static

全部标识为@AfterClass的方法都必定会被执行      全部标识为@After 的方法都必定会被执行,即便在标识为

,即便在标识为@BeforeClass的方法抛出异常       @Before 或者 @Test 的方法抛出异常的的状况下也同样会。

的的状况下也同样会。 

 

@BeforeClass 和 @AfterClass 对于那些比较“昂贵”的资源的分配或者释放来讲是颇有效的,由于他们只会在类中被执行一次。相比之下对于那些须要在每次运行以前都要初始化或者在运行以后都须要被清理的资源来讲使用@Before和@After一样是一个比较明智的选择。

相关文章
相关标签/搜索