java - JUnit 5 中@RuleChain 的等价物是什么?

标签 java junit junit5 junit5-extension-model

  • 我有 2 个“类(class)”规则:MyRule1MyRule2
  • 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
    但在依赖于其他扩展的扩展上没有找到任何内容。

    最佳答案

    报价 Jupiter's documentation :

    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/

    相关文章:

    java - Onejar-maven-插件错误

    java - 获取 LiveData 的初始值总是返回 Null

    spring - 在 SpringExtension 之前执行扩展

    java - 无法注册 MBean [HikariDataSource (testdb)]

    java - Spring 测试模块与 Mockito

    java - testng - 在 testng.xml 中将列表作为参数传递

    java - Android:动画自定义 View

    android - java.lang.IllegalAccessError : Class ref in pre-verified class resolved to unexpected implementation getting while running test project?

    java - JerseyIncation 表达式在类中不可用,但可通过 IntelliJ 调试器中的 Evaluate 表达式访问

    java - 解释 JUnit 测试结果?