为每个测试执行 JUnit5 BeforeAllCallback class
JUnit5 BeforeAllCallback is executed for every test class
我有以下 classes:
public class MyExtension implements BeforeAllCallback, AfterAllCallback {
...
}
@SpringBootTest
@ExtendWith(MyExtension.class)
@ActiveProfiles("test")
class MyService1IT{
...
}
@SpringBootTest
@AutoConfigureMockMvc
@ExtendWith(MyExtension.class)
@ActiveProfiles("test")
class MyService2IT{
...
}
使用 IntelliJ 的 Run All Tests
或 mvn failsafe:integration-test
执行测试时,我可以清楚地看到每个 class 都执行了 beforeAll
和 afterAll
方法。
我怎样才能避免这种情况?我虽然 ExtendWith
只会为这些回调执行一次。
不,ExtendWith 机制只允许您设计可重用的行为,但生命周期与 @BeforeEach
/ @BeforeAll
方法非常相似。
但是没有什么能阻止您在扩展中实现自己的生命周期。
这里有一些代码可以确保它只被调用一次。
private static final AtomicBoolean FIRST_TIME = new AtomicBoolean(true);
// and in your method:
if(FIRST_TIME.getAndSet(false)){
// code here that should only be run once
}
请注意,此解决方案依赖于位于同一虚拟机中/运行。因此,如果每个测试或测试有一个 fork 模式 class,您将需要使用一些外部同步方式。
我有以下 classes:
public class MyExtension implements BeforeAllCallback, AfterAllCallback {
...
}
@SpringBootTest
@ExtendWith(MyExtension.class)
@ActiveProfiles("test")
class MyService1IT{
...
}
@SpringBootTest
@AutoConfigureMockMvc
@ExtendWith(MyExtension.class)
@ActiveProfiles("test")
class MyService2IT{
...
}
使用 IntelliJ 的 Run All Tests
或 mvn failsafe:integration-test
执行测试时,我可以清楚地看到每个 class 都执行了 beforeAll
和 afterAll
方法。
我怎样才能避免这种情况?我虽然 ExtendWith
只会为这些回调执行一次。
不,ExtendWith 机制只允许您设计可重用的行为,但生命周期与 @BeforeEach
/ @BeforeAll
方法非常相似。
但是没有什么能阻止您在扩展中实现自己的生命周期。 这里有一些代码可以确保它只被调用一次。
private static final AtomicBoolean FIRST_TIME = new AtomicBoolean(true);
// and in your method:
if(FIRST_TIME.getAndSet(false)){
// code here that should only be run once
}
请注意,此解决方案依赖于位于同一虚拟机中/运行。因此,如果每个测试或测试有一个 fork 模式 class,您将需要使用一些外部同步方式。