在@After方法中检测Junit测试的失败或错误 [英] Detect Failure or Error of Junit Test in @After method

查看:69
本文介绍了在@After方法中检测Junit测试的失败或错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JUnit中是否有办法在@After注释方法中检测测试用例中是否存在测试失败或错误?

Is there a way in JUnit to detect within an @After annotated method if there was a test failure or error in the test case?

一个丑陋解决方案就是这样:

One ugly solution would be something like that:

boolean withoutFailure = false;

@Test
void test() {
  ...
  asserts...
  withoutFailure = true;
}

@After
public void tearDown() {
   if(!withoutFailuere) {
      this.dontReuseTestenvironmentForNextTest();
   }
}

这是丑陋的,因为需要照顾测试代码中的基础设施(没有失败标志)。

This is ugly because one need to take care of the "infrastructure" (withoutFailure flag) in the test code.

我希望我能在@After方法中获得测试状态!

I hope that there is something where I can get the test status in the @After method!?

推荐答案

如果你有幸使用JUnit 4.9或更高版本, TestWatcher 将完全符合您的要求。

If you are lucky enough to be using JUnit 4.9 or later, TestWatcher will do exactly what you want.

分享并享受!

这篇关于在@After方法中检测Junit测试的失败或错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆