MyRule1
和 MyRule2
MyRule2
取决于 MyRule1
MyRule1
因此,“before”方法应该在 MyRule2
之前运行“之前”方法。 在 JUnit 4 中,它可以通过这种方式实现,通过 RuleChain :
static MyRule1 myRule1 = new MyRule1();
static MyRule2 myRule2 = new MyRule2(myRule1);
@Rule
TestRule ruleChain = RuleChain.outerRule(myRule1)
.around(myRule2);
在 JUnit 5 中,我必须以这种方式实现它:
static MyRule1 myRule1 = new MyRule1();
@RegisterExtension
static MyRule2 myRule2 = new MyRule2(myRule1);
与
MyRule2
:class MyRule2 implements BeforeAllCallback {
private final MyRule1 myRule1;
public MyRule2(MyRule1 myRule1) {
this.myRule1 = myRule1;
}
@Override
public void beforeAll(ExtensionContext extensionContext) {
this.myRule1.beforeAll();
X x = this.myRule1.getX();
// do Rule 2 stuff with x
}
}
就结果而言,它相当于 JUnit 4 的实现。
但我必须明确地手动调用
beforeAll()
MyRule1
的回调在 MyRule2
.我想要那个
MyRule2
不负责MyRule1
执行。我经历了Extension Model documentation of JUnit 5
但在依赖于其他扩展的扩展上没有找到任何内容。
最佳答案
Extensions registered declaratively via
@ExtendWith
will be executed in the order in which they are declared in the source code.
因此,在您的情况下,您应该按以下顺序声明它们:
@ExtendsWith({Rule1.class, Rule2.class})
public class MyTest {
关于java - JUnit 5 中@RuleChain 的等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52646975/