What is the equivalent of ExternalResource and TemporaryFolder in JUnit 5?

后端 未结 5 2406
心在旅途
心在旅途 2021-02-19 02:20

According to the JUnit 5 User Guide, JUnit Jupiter provides backwards compatibility for some JUnit 4 Rules in order to assist with migration.

As stated ab

5条回答
  •  终归单人心
    2021-02-19 03:22

    As far as I understood, there can be no one to one mapping from ExternalResource to an equivalent in JUnit5. The concepts just don't fit. In JUnit4, the ExternalResource basically gives you a before and an after callback, but within the rule, you have no control about what before and after actually means. You could use it with @Rule or with @ClassRule.

    In JUnit5, the extension is defined to hook in specific extension points and thus the 'when' is well defined.

    Another difference in concepts would be, that you can have a state in JUnit4 rules, but your JUnit5 extensions shouldn't have any state. Instead, all state should go to the execution context.

    Nevertheless, here is an option I came along with, where before and after relates to each test method:

    public abstract class ExternalResourceExtension 
      implements BeforeTestExecutionCallback, AfterTestExecutionCallback {
        @Override
        public void beforeTestExecution(ExtensionContext context) throws Exception {
            before(context);
        }
    
        @Override
        public void afterTestExecution(ExtensionContext context) throws Exception {
            after(context);
        }
    
        protected abstract void before(ExtensionContext context);
    
        protected abstract void after(ExtensionContext context);
    }
    

提交回复
热议问题