gpt4 book ai didi

java - 如何创建自定义 JUnit5 扩展

转载 作者:行者123 更新时间:2023-12-05 04:09:19 25 4
gpt4 key购买 nike

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

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

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

然后,我可以使用 JUnit5

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

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

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

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

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在 Junit5。事实上这就是 @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 {

关于java - 如何创建自定义 JUnit5 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46194482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com