依赖及jar包:
junit-4.12.jar
hamcrest-core-1.3.jar
junit junit 4.12
简单用例:
import static org.junit.Assert.assertArrayEquals;import static org.junit.Assert.assertTrue;import org.junit.After;import org.junit.AfterClass;import org.junit.Before;import org.junit.BeforeClass;import org.junit.Test;public class TestJ{ public TestJ(){ System.out.println("构造方法"); } @BeforeClass public static void bc(){ System.out.println("befor class"); } @Before public void b(){ System.out.println("befor"); } @Test public void t1(){ System.out.println("test1"); assertTrue(2 == com.lwt.test.slf4j.main.Test.add(1,2)); assertArrayEquals(new String[]{ "1","a"}, new String[]{ "1","a"}); } @Test public void t2(){ System.out.println("test2"); assertTrue(2 == 1+1); } @After public void a(){ System.out.println("after"); } @AfterClass public static void ac(){ System.out.println("after class"); }}
输出:
befor class构造方法befortest1after构造方法befortest2afterafter class
总结:
@BeforeClass
、 @AfterClass
需要为静态,且之执行一次。@Before
、 @After
针对每个测试方法前后执行。