junit
カスタムテストルール
サーチ…
備考
どちらにもメリットがあります。 ExternalResource拡張すると便利です。特に、何かを設定するためにbefore()が必要な場合に便利です。
しかし、 before()メソッドはtry...finally外側で実行されるため、 after()でクリーンアップを行う必要があるコードは実行されません。 before()実行。
これはExternalResource内部をどのように見えるかです:
before();
try {
base.evaluate();
} finally {
after();
}
明らかに、テスト自体または別のネストされたルールによって例外がスローされた場合でも、afterは引き続き実行されます。
実装によるカスタム@TestRule
これは、ルール内で拡張したいクラスがある場合に特に便利です。より便利な方法については、下記の例を参照してください。
import org.junit.rules.TestRule;
import org.junit.runners.model.Statement;
public class AwesomeTestRule implements TextRule {
@Override
public Statement apply(Statement base, Description description) {
return new AwesomeStatement(base);
}
private static class AwesomeStatement extends Statement {
private Statement base;
public AwesomeStatement(Statement base) {
this.base = base;
}
@Override
public void evaluate() throws Throwable {
try {
// do your magic
base.evaluate(); // this will call Junit to run an individual test
} finally {
// undo the magic, if required
}
}
}
}
カスタム@TestRule(拡張機能別)
JUnitには@TestRule抽象実装が@TestRuleており、より簡単な方法でルールを書くことができます。これはExternalResourceと呼ばれ、次のように拡張できる2つの保護されたメソッドを提供します:
public class AwesomeTestRule extends ExternalResource {
@Override
protected void before() {
// do your magic
}
@Override
protected void after() {
// undo your magic, if needed
}
}
Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow