fro*_*die 85 java testing junit
我正在大型代码库上运行JUnit测试,我一直意识到有时候我会得到"错误",而有时我会得到"失败".有什么不同?
fro*_*die 114
好吧,我刚刚注意到一种模式,并认为我已经弄明白了(如果我错了,请纠正我).在我看来,失败是你的测试用例失败的时候 - 即你的断言不正确.错误是在尝试实际运行测试时发生的意外错误 - 异常等.
Nee*_*eel 13
如果您的测试抛出了一个异常,该异常不会通过Junit中的Assertion框架冒出来,则会将其报告为错误.例如,NullPointer或ClassNotFound异常将报告错误:
String s = null;
s.trim();
Run Code Online (Sandbox Code Playgroud)
要么,
try {
// your code
} catch(Exception e) {
// log the exception
throw new MyException(e);
}
Run Code Online (Sandbox Code Playgroud)
话虽如此,以下将报告失败:
Assert.fail("Failure here");
Run Code Online (Sandbox Code Playgroud)
要么,
Assert.assertEquals(1, 2);
Run Code Online (Sandbox Code Playgroud)
甚至:
throw new AssertionException(e);
Run Code Online (Sandbox Code Playgroud)
这取决于您使用的Junit版本.Junit 4-将区分故障和错误,但Junit 4仅将故障简化为故障.
以下链接提供了更有趣的输入:
http://www.devx.com/Java/Article/31983/1763/page/2
来自“使用JUnit的Java 8中的实用单元测试”:
JUnit中的断言(或断言)是您放入测试的静态方法调用。每个断言都是验证某些条件成立的机会。如果断言的条件不成立,则测试将在此处停止,并且JUnit报告测试失败。
(也有可能,当JUnit运行您的测试时,会引发而不捕获异常。在这种情况下,JUnit报告一个测试错误。)
我已经评论了引发测试错误和测试失败的行。
@Test
public void testErrorVsTestFailure() {
final String sampleString = null;
assertEquals('j', sampleString.charAt(0) );
//above line throws test error as you are trying to access charAt() method on null reference
assertEquals(sampleString, "jacob");
//above line throws Test failure as the actual value-a null , is not equal to expected value-string "jacob"
}
Run Code Online (Sandbox Code Playgroud)
因此,每当您遇到异常时,Junit 都会显示测试错误,并在您的预期结果值与您的实际值不匹配时显示测试失败