你可以用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");
}
}
注意你手動調用拆卸,所以你不希望有方法@After註解,否則它被調用兩次。有關更多示例,請參閱ExternalResource.java和ExpectedException.java。
非常感謝。這是很好的幫助..正是我需要.. – vpradhan