私のjunitテストケースで、次のような条件付きティアダウンが必要です
@Test
testmethod1()
{
//condition to be tested
}
@Teardown
{
//teardown method here
}
分解では、次のような状態にしたい
if(pass)
then execute teardown
else skip teardown
junitを使用してそのようなシナリオは可能ですか?
私のjunitテストケースで、次のような条件付きティアダウンが必要です
@Test
testmethod1()
{
//condition to be tested
}
@Teardown
{
//teardown method here
}
分解では、次のような状態にしたい
if(pass)
then execute teardown
else skip teardown
junitを使用してそのようなシナリオは可能ですか?
これはTestRuleで実行できます。TestRule
テスト メソッドの前後にコードを実行できます。テストが例外 (または失敗したアサーションの場合は AssertionError) をスローした場合、テストは失敗したので、tearDown() をスキップできます。例は次のとおりです。
public class ExpectedFailureTest {
public class ConditionalTeardown implements TestRule {
public Statement apply(Statement base, Description description) {
return statement(base, description);
}
private Statement statement(final Statement base, final Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
try {
base.evaluate();
tearDown();
} catch (Throwable e) {
// no teardown
throw e;
}
}
};
}
}
@Rule
public ConditionalTeardown conditionalTeardown = new ConditionalTeardown();
@Test
public void test1() {
// teardown will get called here
}
@Test
public void test2() {
Object o = null;
o.equals("foo");
// teardown won't get called here
}
public void tearDown() {
System.out.println("tearDown");
}
}
TearDown を手動で呼び出しているため、メソッドに @After アノテーションを付けたくないことに注意してください。そうしないと、2 回呼び出されます。その他の例については、ExternalResource.javaおよびExpectedException.javaを参照してください。