博客中的部分字句引自慕课网的《JUnit-Java单元测试必备工具》公开课程。
首先创建如下代码:
@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...");
}
下面逐一对运行顺序相关注解进行解释。
1.@BeforeClass修饰的方法会在所有方法被调用前执行,而且该方法是静态的,所以当测试类被加载后就会运行它,而且在内存中它只会存在一份实例,它比较适合加载配置文件。
2.@AfterClass所修饰的方法会在所有方法被调用后执行,通常用来对资源的清理,如关闭数据库的链接。
3.@Before会在每个测试方法执行前执行一次。
4.@After会在每个测试方法的前后各执行一次。
This is beforeClass...
This is before...
This is test1...
This is after...
This is before...
This is test2...
This is after...
This is afterClass...
以上就是JunitTest各注解的运行流程。