如何创建自定义 JUnit5 扩展

How to create custom JUnit5 Extensions

是否可以像我在 JUnit4 中创建 @Rule 一样创建自定义扩展?

public class MockMetadataServiceRule extends ExternalResource {   
    @Override
    protected void before() throws Throwable {
        //some setup
    }

    @Override
    protected void after() {
       // some teardown
    }
}

然后,我可以在测试 class 和 JUnit5

中执行此操作
@BeforeAll
public static void init() {
    MetadataServiceFactory.setService(MockitoMockMetadataService.getMock());
}

@AfterAll
public static void teardown() {
    MetadataServiceFactory.setService(null);
}

但我想你现在可以@ExtendWith(MyExtension.class)

编辑: 我的扩展示例以防@nullpointer link 消失。谢谢。

public class MockMetadataServiceExtension implements BeforeAllCallback, AfterAllCallback {

    @Override
    public void afterAll(ExtensionContext extensionContext) throws Exception {
        MetadataServiceFactory.setService(null);
    }

    @Override
    public void beforeAll(ExtensionContext extensionContext) throws Exception {
        MetadataServiceFactory.setService(MockitoMockMetadataService.getMock());
    }
}

。可以创建 custom extensions in Junit5. In fact that is what @ExtendWith 用于 :

To register a custom YourExtension for all tests in a particular class and its subclasses, you would annotate the test class as follows.

@ExtendWith(YourExtension.class)
class YourTests {
    // ...
}

可在 spring-framework.

找到 BeforeAllCallbackAfterAllCallback 的示例

Multiple extensions can be registered together like this:

@ExtendWith({ YourExtension1.class, YourExtension2.class })
class YourTests {