一,验证Junit测试方法的流程
1,在test/com.duo.util右键,新建测试类
2,生成后的代码:
package com.duo.util; import static org.junit.Assert.*; import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test; public class JunitFlowTest { @BeforeClass
public static void setUpBeforeClass() throws Exception {
System.out.println("This is @BeforeClass...");
} @AfterClass
public static void tearDownAfterClass() throws Exception {
System.out.println("This is AfterClass...");
} @Before
public void setUp() throws Exception {
System.out.println("This is Before...");
} @After
public void tearDown() throws Exception {
System.out.println("This is After...");
} @Test
public void test1(){
System.out.println("This is test1...");
} @Test
public void test2(){
System.out.println("This is test2...");
} }
运行结果:
This is @BeforeClass...
This is Before...
This is test1...
This is After...
This is Before...
This is test2...
This is After...
This is AfterClass...
二,总结:
1,@BeforeClass修饰的方法会在所有方法被调用前被执行;而且该方法是静态的,所以当测试类被加载后接着就会运行它,而且在内存中它只会存在一份实例,它比较适合加载配置文件;比如数据的连接文件等;
2,@AfterClass所修饰的方法通常用来对资源的清理,如数据库的关闭;
3,@Before和@After会在每个测试方法前后执行;通常被称为固定代码(fixure),就是一定会执行的代码.