在使用 Junit5 的 spock 单元测试中不考虑 @Rule 注释

@Rule annotation is not considered in spock unit tests using Junit5

我正在尝试迁移我的项目以使用 Junit5。到目前为止,我一直在使用 class “LogSpy”,它基本上拦截并保存所有日志,以便可以轻松地对其进行测试。使用 Junit4 和 Spock 测试,我能够通过使用 @Rule 注释(即使它在 Spock 测试中)来初始化我的日志拦截器 class。迁移到 Junit5 后,此注释似乎没有初始化所需的日志拦截器 class,我找不到原因。为什么会这样? Junit4 和 5 关于 @Rule 注解有什么区别?有办法解决这个问题吗?

这就是我初始化 LogSpy 的方式 class。它在 JUnit 单元测试中初始化,但在 Spock 测试中不初始化。

@Rule
public LogSpy logSpy = new LogSpy()

来自release notes

JUnit 4 Rules are not supported by spock-core anymore, however, there is a new spock-junit4 module that provides best effort support to ease migration.

简而言之,如果您仍然需要使用 JUnit 4 规则,请添加 spock-junit4 依赖项。

从长远来看,我建议迁移到 Spock 本机 extensions