后端——框架——测试框架——junit——生命周期
本篇包含两个部分。
第一部分,介绍测试类的生命周期
第二部分,介绍测试方法的生命周期。
1、测试类
默认情况下,测试类会为每个测试案例方法创建一个实例,即使案例方法上有@Disabled等类似的注解。
在类上添加@TestInstance注解,它的值有两种:
LIFE_CYCLE.PER_CLASS,它只会创建一个实例。
LIFE_CYCLE.PER_METHOD, 每运行一个测试方法,创建一个实例,是默认值。
junit.jupiter.testinstance.lifecycle.default = per_class,默认的值为per_method。
当实例创建之后,若实现TestInstancePostProcessor接口,可以自定义初始化过程。
当实例销毁之前,若实现TestInstancePreDestroyCallback接口,可以在销毁之前回收资源。
类似于spring框架中的init-method和destory-method,@PostConstruct, @PreDestory机制。
2、测试方法
与生命周期相关的方法有:
@BeforeAll:在所有测试方法开始前运行一次,且只运行一次。
@BeforeEach: 在每个测试案例开始前运行一次。对于多次运行的,每运行完一次算一次。
@AfterEach:在每个测试案例结束后运行一次。
@AfterAll:在所有案例结束后运行一次。
与生命周期相关的接口有:
BeforeXXCallback,AfterXXCallback:在对应的方法开始之前运行,结束之后运行。
InvocationInterceptor:拦截器。
假设所有都存在,它们的顺序为:
execute postProcessTestInstance method execute Before all tests execute before Each tests execute beforeTestExecution method execute test case method 1 times execute afterTestExecution method execute After Each tests execute before Each tests execute beforeTestExecution method execute test case method 2 times execute afterTestExecution method execute After Each tests execute After all tests execute preDestroyTestInstance method
上述示例为@RepeatedTest,次数为2。它们的层次结构依次是:
类生命周期
Before All
BeforeXXCallback
InvocationInterceptor
测试方法
注:BeforeXXCallback,InvocationInterceptor, TestInstancePostProcessor等接口属于扩展,需要注册才能生效.