我扩展了dsaff的答案,以解决TestRule
无法在测试方法执行和后续方法执行之间执行某些代码的问题。因此,使用简单的MethodRule
,不能使用此规则提供在@After
带注释的方法中使用的成功标志。
我的想法是黑客!无论如何,这是使用TestRule
(延伸TestWatcher
)。 A TestRule
将获得有关测试失败或成功的知识。然后,我的TestRule
将扫描该类中所有用我的新AfterHack
批注注释的方法,并使用成功标志调用该方法。
AfterHack
注释
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Retention(RUNTIME)
@Target(METHOD)
public @interface AfterHack {}
AfterHackRule
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
public class AfterHackRule extends TestWatcher {
private Object testClassInstance;
public AfterHackRule(final Object testClassInstance) {
this.testClassInstance = testClassInstance;
}
protected void succeeded(Description description) {
invokeAfterHackMethods(true);
}
protected void failed(Throwable e, Description description) {
invokeAfterHackMethods(false);
}
public void invokeAfterHackMethods(boolean successFlag) {
for (Method afterHackMethod :
this.getAfterHackMethods(this.testClassInstance.getClass())) {
try {
afterHackMethod.invoke(this.testClassInstance, successFlag);
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
throw new RuntimeException("error while invoking afterHackMethod "
+ afterHackMethod);
}
}
}
private List<Method> getAfterHackMethods(Class<?> testClass) {
List<Method> results = new ArrayList<>();
for (Method method : testClass.getMethods()) {
if (method.isAnnotationPresent(AfterHack.class)) {
results.add(method);
}
}
return results;
}
}
用法:
public class DemoTest {
@Rule
public AfterHackRule afterHackRule = new AfterHackRule(this);
@AfterHack
public void after(boolean success) {
System.out.println("afterHack:" + success);
}
@Test
public void demofails() {
Assert.fail();
}
@Test
public void demoSucceeds() {}
}
顺便说一句:
- 1)希望有在Junit5
更好的解决方案
- 2)更好的方法是在所有使用规则TestWatcher代替@Before和@After方法的(即我读dsaff的答案的方式)
@see
是不是你的'@ Before'方法以确保环境设置正确的每一个测试护理? –
@Vineet Reynolds:是和否:我正在使用Selemium2/Webdriver进行测试,我想重新使用驱动程序。但是如果之前的测试没有任何错误,我只想重用。 – Ralph
好的,我目前的问题。我试图避免国旗。希望看到其他答案。如果我遇到一个合理的解决方案,我会发布我的。 –