Extension机制介绍
Junit5的扩展机制主要是ExtensionContext、Namespace、Store的使用,以及对扩展的注册
使用案例
可以通过实现BeforeAllCallback和AfterAllCallback两个接口为自己的Extension增加前置和后置处理能力
public class NyExtension implements BeforeAllCallback, AfterAllCallback {
private static final SftpServerTestSupport sftpServerTestSupport = new SftpServerTestSupport();
/**
* Callback that is invoked once <em>before</em> all tests in the current
* container.
*
* @param context the current extension context; never {@code null}
*/
@Override
public void beforeAll(ExtensionContext context) throws Exception {
}
/**
* Callback that is invoked once <em>after</em> all tests in the current
* container.
*
* @param context the current extension context; never {@code null}
*/
@Override
public void afterAll(ExtensionContext context) throws Exception {
}
}
在测试类使用@ExtendWith可以对扩展进行注册
@ExtendWith(MyExtension.class)
class MyTest {
……
}
Extension源码简单解读
ExtensionContext
测试上下文。它是整个扩展机制的核心,每个扩展点的扩展方法都需要一个ExtensionContext 实例参数,用于获取执行的测试用例的信息和与Junit引擎进行交互。
测试执行的时候Jupiter会生成一个测试节点树(ide里面也显示),每个@Test测试方法都是这个树上面的一个叶子节点。每个节点都关联一个Context
Optional<ExtensionContext> getParent();
ExtensionContext getRoot();
ExtensionContext提供获取父节点和根节点的方法。
Optional<AnnotatedElement> getElement();
Optional<Class<?>> getTestClass();
Optional<Method> getTestMethod();
……
还提供了一些获取测试对应的类、方法的api
Store getStore(Namespace namespace);
还提供了获取Store的能力
ExtensionContext.Store
ExtensionContext的内部类。
ExtensionContext是无状态的,并且在任何状态下都可以写入store或者从store获取对应的数据信息
Object get(Object key);
void put(Object key, Object value);
提供了一些基础的put、get方法,就像一个map一样提供方法
ExtensionContext.Store.CloseableResource
Store的内部类,只提供了一个方法
void close() throws Throwable;
用于在测试完成后关闭一些底层资源
NamespaceAwareStore
实现自ExtensionContext.Store
,这里开始引入了namespace的概念
private final ExtensionValuesStore valuesStore;
private final Namespace namespace;
评论区