TestRule
は、テストメソッドの実行とアフターメソッドの実行の間にあるコードを実行できないという問題を解決するためにdsaffの答えを拡張しています。だから簡単なMethodRule
@After
注釈付きメソッドで使用されている成功フラグを提供するために、このルールを使用することはできません。
私の考えはハックです!とにかく、TestRule
(extend TestWatcher
)を使用します。 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() {}
}
BTW
:
- 1)うまくいけばJunit5
- 2のよりよい解決策がある)より良い方法は全く代わり@Beforeと@After方法TestWatcherルールを使用することである(つまり私はdsaffの答えを読む方法)
@see
があなたの 'Before'方法@環境は、すべてのテストのために正しく設定されていることを保証するの世話をしていませんか? –
@Vineet Reynolds:はい、いいえ:Selemium2/Webdriverでテストしていますが、ドライバを再利用したいと思います。しかし、前のテストでもエラーがなければ、再利用したいだけです。 – Ralph
ああ、私の現在の問題。私はこの旗を避けようとしている。他の答えを見ることを願っています。私は合理的な解決策に遭遇した場合、私は投稿します。 –