JUnit

如果你正在使用 JUnit 執行,則可以擴充套件 TestWatcher 類:

public class TestRules extends TestWatcher {

    @Override
    protected void failed(Throwable e, Description description) {
        // This will be called whenever a test fails.
    }

所以在你的測試類中你可以簡單地呼叫它:

public class testClass{

@Rule
public TestRules testRules = new TestRules();

@Test
public void doTestSomething() throws Exception{
    // If the test fails for any reason, it will be caught be testrules.
}