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

后端 未结 5 2412
心在旅途
心在旅途 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:15

    Temporary folders now have a solution in the way of @TempDir. However, what about the idea behind ExternalResources in general? Perhaps it's for a mock database, a mock HTTP connection, or some other custom resource you want to add support for?

    The answer, it turns out is you can use the @RegisterExtension annotation to achieve something quite similar.

    Example of use:

    /**
     * This is my resource shared across all tests
     */
    @RegisterExtension
    static final MyResourceExtension MY_RESOURCE = new MyResourceExtension();
    
    /**
     * This is my per test resource
     */
    @RegisterExtension
    final MyResourceExtension myResource = new MyResourceExtension();
    
    @Test
    void test() {
        MY_RESOURCE.doStuff();
        myResource.doStuff();
    }
    

    And here's the basic scaffolding of MyResourceExtension:

    public class MyResourceExtension implements BeforeAllCallback, AfterAllCallback,
            BeforeEachCallback, AfterEachCallback {
    
        private SomeResource someResource;
    
        private int referenceCount;
    
        @Override
        public void beforeAll(ExtensionContext context) throws Exception {
            beforeEach(context);
        }
    
        @Override
        public void afterAll(ExtensionContext context) throws Exception {
            afterEach(context);
        }
    
        @Override
        public void beforeEach(ExtensionContext context) throws Exception {
            if (++referenceCount == 1) {
                // Do stuff in preparation
                this.someResource = ...;
            }
        }
    
        @Override
        public void afterEach(ExtensionContext context) throws Exception {
            if (--referenceCount == 0) {
                // Do stuff to clean up
                this.someResource.close();
                this.someResource = null;
            }
        }
    
        public void doStuff() {
            return this.someResource.fooBar();
        }
    
    }
    

    You could of course wrap this all up as an abstract class and have MyResourceExtension implement just protected void before() and protected void after() or some such, if that's your thing, but I'm omitting that for brevity.

提交回复
热议问题