JUnit中的失败和错误有什么区别?

我正在一个庞大的代码库上运行JUnittesting,而且我一直在意识到,有时我会得到“错误”,而其他时候我会得到“失败”。 有什么不同?

好吧,我刚刚注意到了一个模式,并认为我已经明白了(纠正我,如果我错了)。 在我看来,失败是当你的testing案例失败 – 即你的断言是不正确的。 错误是尝试实际运行testing时发生的意外错误 – 例外等

如果您的testing引发了一个exception,它不会通过Junit中的Assertion框架冒出来,它会被报告为错误。 例如,NullPointer或ClassNotFoundexception将报告一个错误:

 String s = null; s.trim(); 

要么,

 try { // your code } catch(Exception e) { // log the exception throw new MyException(e); } 

话虽如此,以下将报告失败:

 Assert.fail("Failure here"); 

要么,

 Assert.assertEquals(1, 2); 

甚至:

 throw new AssertionException(e); 

这取决于您使用的Junit版本。 Junit 4将区分故障和错误,但Junit 4将其简化为故障。

以下链接提供更有趣的input:

http://www.devx.com/Java/Article/31983/1763/page/2

从“用JUnit实现Java 8中的实用unit testing”:

JUnit中的断言(或断言)是静态的方法调用,你放入你的testing。 每个断言都是validation某些条件成立的机会。 如果声明的条件不成立,则testing停在那里,JUnit报告testing失败。

(当JUnit运行你的testing时,也可能抛出一个exception,而不是被捕获,在这种情况下,JUnit报告一个testing错误。)

下面的testing解释了testing错误与testing失败的区别。

我已经评论了引发testing错误和testing失败的行。

  @Test public void testErrorVsTestFailure() { String s =new String("jacob"); s=null; //assertEquals(java.lang.Object expected, java.lang.Object actual) assertEquals('j', s.charAt(0) ); //above line throws test error as you are trying to access charAt() method on null reference assertEquals(s, "jacob")); //above line throws Test failure as the actual value-a null , is not equal to expected value-string "jacob" } 

所以无论何时出现exception,Junit都会显示testing错误,并在您的预期结果值与您的实际值不匹配时testing失败

源类:JUnitReportReporter.java

 public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String defaultOutputDirectory) { //...... for (ITestResult tr : (Set) entry.getValue()) { TestTag testTag = new TestTag(); boolean isSuccess = tr.getStatus() == 1; if (!(isSuccess)) { if (tr.getThrowable() instanceof AssertionError) ++errors; else { ++failures; } } } 

正如你可以在上面的方法中看到的那样

tr.getThrowable()instanceof AssertionError

错误计数在AssertionError实例中增加,否则(任何Throwable)计为失败。