我们有一个单元测试父Base类,以及一组扩展基类的单元测试。我希望每个失败的测试都能调用特定的方法。可以在某处创建“钩子”或某种东西,即传递测试不会调用此方法,但是在执行结束时测试失败。
答案 0 :(得分:5)
你应该看一下TestWatcher类。 创建自己的类,扩展TestWatcher,覆盖失败的(Throwable e,Description description)方法并为测试添加规则。
public class MyWatcher extends TestWatcher {
@Override
protected void failed(Throwable e, Description description) {
callMyMethod();
}
}
你的考试:
public class MyTest {
@Rule
public MyWatcher rule = new MyWatcher ();
@Test
public myTest(){...}
}
TestWatcher中也有一个有用的方法,比如starting()和finished()