我想在每个 Spring Boot JUnit 测试用例之前使用 TestExecutionListener 初始化状态。此初始化需要在调用 JUnit @Rule
的相应回调之前运行。
我本以为 beforeTestMethod
适合这个,因为它的 JavaDoc 注释说
Pre-processes a test before execution of before lifecycle callbacks of the underlying test framework
规则将“之前”回调贡献给测试,因此我预计 beforeTestMethod
在规则之前执行。然而,调试器显示情况并非如此!
这是我的代码的结构:
@RunWith(SpringRunner.class)
@SpringBootTest
@TestExecutionListeners(listeners = MyTestExecutionListener.class, mergeMode = MergeMode.MERGE_WITH_DEFAULTS)
public class MyTest {
@Autowired
@Rule
public MyRule rule;
@Test
public void test1() {
// ...
}
// ... more tests
}
public class MyTestExecutionListener implements TestExecutionListener {
@Override
public void beforeTestMethod(TestContext testContext) {
// ...
}
}
@Component
public class AutoLogin extends ExternalResource {
@Override
protected void before() {
// ...
}
}
我希望方法按顺序执行
beforeTestMethod()
rule.before()
test1()
但实际顺序是
rule.before()
beforeTestMethod()
test1()
您知道我做错了什么,或者我应该使用其他哪种 TestExecutionListener
方法吗?
最佳答案
如果您想在执行 Rule
之前初始化每个测试的状态,则应使用 TestExecutionListener
的 prepareTestInstance
方法> 界面。
@Override
public void prepareTestInstance(TestContext testContext) {
System.out.println("inside prepareTestInstance");
}
这样,您将按以下顺序执行方法:
prepareTestInstance()
rule.before()
test1()
请注意,prepareTestInstance
将在每个测试方法之前执行
关于java - 在 JUnit 规则运行之前使用 Spring TestExecutionListener 初始化状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56342996/