In JUnit 5, how to run code before all tests

后端 未结 5 2102
悲&欢浪女
悲&欢浪女 2020-12-03 00:34

The @BeforeAll annotation marks a method to run before all tests in a class.

http://junit.org/junit5/docs/current/user-guide/#writing-tests-ann

5条回答
  •  佛祖请我去吃肉
    2020-12-03 01:08

    This is now possible in JUnit5 by creating a custom Extension, from which you can register a shutdown hook on the root test-context.

    Your extension would look like this;

    import org.junit.jupiter.api.extension.BeforeAllCallback;
    import org.junit.jupiter.api.extension.ExtensionContext;
    import static org.junit.jupiter.api.extension.ExtensionContext.Namespace.GLOBAL;
    
    public class YourExtension implements BeforeAllCallback, ExtensionContext.Store.CloseableResource {
    
        private static boolean started = false;
    
        @Override
        public void beforeAll(ExtensionContext context) {
            if (!started) {
                started = true;
                // Your "before all tests" startup logic goes here
                // The following line registers a callback hook when the root test context is shut down
                context.getRoot().getStore(GLOBAL).put("any unique name", this);
            }
        }
    
        @Override
        public void close() {
            // Your "after all tests" logic goes here
        }
    }
    

    Then, any tests classes where you need this executed at least once, can be annotated with:

    @ExtendWith({YourExtension.class})
    

    When you use this extension on multiple classes, the startup and shutdown logic will only be invoked once.

提交回复
热议问题