您可以创建自己的AfterEachCallback 扩展并将其应用于所需的测试方法。此扩展将在应用它的每个测试后执行。然后,使用自定义注释,您可以将特定的清理方法与特定的测试联系起来。这是扩展的示例:
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.List;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ExtensionContext.Namespace;
import org.junit.jupiter.api.extension.ExtensionContext.Store;
import org.junit.platform.commons.support.AnnotationSupport;
import org.junit.platform.commons.support.HierarchyTraversalMode;
public class CleanupExtension implements AfterEachCallback {
private static final Namespace NAMESPACE = Namespace.create(CleanupExtension.class);
private static boolean namesMatch(Method method, String name) {
return method.getAnnotation(CleanMethod.class).value().equals(name);
}
private static Exception suppressOrReturn(final Exception previouslyThrown,
final Exception newlyThrown) {
if (previouslyThrown == null) {
return newlyThrown;
}
previouslyThrown.addSuppressed(newlyThrown);
return previouslyThrown;
}
@Override
public void afterEach(final ExtensionContext context) throws Exception {
final Method testMethod = context.getRequiredTestMethod();
final Cleanup cleanupAnno = testMethod.getAnnotation(Cleanup.class);
final String cleanupName = cleanupAnno == null ? "" : cleanupAnno.value();
final List<Method> cleanMethods = getAnnotatedMethods(context);
final Object testInstance = context.getRequiredTestInstance();
Exception exception = null;
for (final Method method : cleanMethods) {
if (namesMatch(method, cleanupName)) {
try {
method.invoke(testInstance);
} catch (Exception ex) {
exception = suppressOrReturn(exception, ex);
}
}
}
if (exception != null) {
throw exception;
}
}
@SuppressWarnings("unchecked")
private List<Method> getAnnotatedMethods(final ExtensionContext methodContext) {
// Use parent (Class) context so methods are cached between tests if needed
final Store store = methodContext.getParent().orElseThrow().getStore(NAMESPACE);
return store.getOrComputeIfAbsent(
methodContext.getRequiredTestClass(),
this::findAnnotatedMethods,
List.class
);
}
private List<Method> findAnnotatedMethods(final Class<?> testClass) {
final List<Method> cleanMethods = AnnotationSupport.findAnnotatedMethods(testClass,
CleanMethod.class, HierarchyTraversalMode.TOP_DOWN);
for (final Method method : cleanMethods) {
if (method.getParameterCount() != 0) {
throw new IllegalStateException("Methods annotated with "
+ CleanMethod.class.getName() + " must not have parameters: "
+ method
);
}
}
return cleanMethods;
}
@ExtendWith(CleanupExtension.class)
@Retention(RUNTIME)
@Target(METHOD)
public @interface Cleanup {
String value() default "";
}
@Retention(RUNTIME)
@Target(METHOD)
public @interface CleanMethod {
String value() default "";
}
}
然后您的测试类可能如下所示:
import org.junit.jupiter.api.Test;
class Tests {
@Test
@CleanupExtension.Cleanup
void testWithExtension() {
System.out.println("#testWithExtension()");
}
@Test
void testWithoutExtension() {
System.out.println("#testWithoutExtension()");
}
@Test
@CleanupExtension.Cleanup("alternate")
void testWithExtension_2() {
System.out.println("#testWithExtension_2()");
}
@CleanupExtension.CleanMethod
void performCleanup() {
System.out.println("#performCleanup()");
}
@CleanupExtension.CleanMethod("alternate")
void performCleanup_2() {
System.out.println("#performCleanup_2()");
}
}
运行Tests 我得到以下输出:
#testWithExtension()
#performCleanup()
#testWithExtension_2()
#performCleanup_2()
#testWithoutExtension()
此扩展将应用于任何带有CleanupExtension.Cleanup 或ExtendWith(CleanupExtension.class) 注释的测试方法。前一个注解的目的是将配置与同样应用扩展的注解结合起来。然后,在每个测试方法之后,扩展将调用类层次结构中使用CleanupExtension.CleanMethod 注释的任何方法。 Cleanup 和 CleanMethod 都具有 String 属性。该属性是“名称”,只有与Cleanup 测试具有匹配“名称”的CleanMethods 才会被执行。这允许您将特定的测试方法链接到特定的清理方法。
有关 JUnit Jupiter 扩展的更多信息,请参阅§5 of the User Guide。另外,对于CleanupExtension.Cleanup,我正在使用§3.1.1 中描述的元注释/组合注释功能。
请注意,这比 @Roman Konoval 给出的the answer 更复杂,但如果您必须多次执行此类操作,它可能对用户更友好。但是,如果您只需要为一两个测试课程执行此操作,我推荐 Roman 的答案。