首先看一下这几个注解在junit4和junit5版本不同的写法
junit4 | junit5 | 特点 |
---|---|---|
@BeforeClass | @BeforeAll | 在当前类的所有测试方法之前执行。注解在【静态方法】上。 |
@AfterClass | @AfterAll | 在当前类中的所有测试方法之后执行。注解在【静态方法】上。 |
@Before | @BeforeEach | 在每个测试方法之前执行。注解在【非静态方法】上。 |
@After | @AfterEach | 在每个测试方法之后执行。注解在【非静态方法】上。 |
表的意思表现的很明白,接下来给大家一个实例:
import org.junit.*;
public class TestJunitAnnotation {
@BeforeClass
public static void beforeClass(){
System.out.println("before class:begin this class*************");
}
@AfterClass
public static void afterClass(){
System.out.println("after class:end this class--------------");
}
@Before
public void before(){
System.out.println("before:begin test");
}
@After
public void after(){
System.out.println("after:end test");
}
@Test
public void Test(){
System.out.println("[this is a test!]");
}
@Test
public void Test2(){
System.out.println("[this is another test!]");
}
}
执行该测试方法TestJunitAnnotation,控制台输出:
正如我们最上方表格所示,@BeforeClass是在所有测试方法前,执行一次,而@Before是在每个测试方法前都会执行,同理得After
参考文章:https://blog.csdn.net/iexploration/article/details/82023893