java - 在 JUnit 规则运行之前使用 Spring TestExecutionListener 初始化状态

标签 java spring spring-test

我想在每个 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 之前初始化每个测试的状态,则应使用 TestExecutionListenerprepareTestInstance 方法> 界面。

@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/

相关文章:

java - 从资源文件夹获取图像时出错

java - 添加 ContentNegotiatingViewResolver 时出现内部服务器错误

java - 如何在java中使用junit mockito处理依赖于抽象方法的测试类

java - 提高机器学习 JAVA 程序的速度

java尝试将平面图像转换为缓冲图像,但颜色模型不兼容

java - 在 Spring 中使用 AspectJ 捕获映射器方法内的 setter

java - 如何使用spring验证junit中的方法调用typsafe?

java - 无法使用 @springboot.web.CommentsApiControllerTest$WithMockCustomUser 创建 SecurityContext

java - 实现 ResponseErrorHandler 接口(interface)

mysql - 具有不同大小写的属性表现异常