Java 如果代码中有任何异常,如何使 Junit 测试用例失败?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36832289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make a Junit test case fail if there is any exception in the code?
提问by Rishi Arora
I wrote a Junit test to unit test my code. I want my Junit test case to fail when I get any exception in my code. I tried using an assert statement, but even when I get an exception in my code, my Junit test case is passing. Please can anyone tell me how I can achieve this? Thanks.
我编写了一个 Junit 测试来对我的代码进行单元测试。当我的代码中出现任何异常时,我希望我的 Junit 测试用例失败。我尝试使用 assert 语句,但即使我的代码出现异常,我的 Junit 测试用例也能通过。请谁能告诉我如何实现这一目标?谢谢。
采纳答案by kpie
You can assert that a global variable "excepted" = null or something like that and initialize it to equal some information string in the catch block.
您可以断言全局变量“excepted”= null 或类似的东西,并将其初始化为等于 catch 块中的某个信息字符串。
回答by Vinay
I strongly recommend that you must test your functionality only. If an exception is thrown, the test will automatically fail. If no exception is thrown, your tests will all turn up green.
我强烈建议您必须仅测试您的功能。如果抛出异常,测试将自动失败。如果没有抛出异常,您的测试将全部变为绿色。
But if you still want to write the test code that should fail the in case of exceptions, do something like :-
但是,如果您仍然想编写在异常情况下应该失败的测试代码,请执行以下操作:-
@Test
public void foo(){
try{
//execute code that you expect not to throw Exceptions.
}
catch(Exception e){
fail("Should not have thrown any exception");
}
}
回答by Thomas Kl?ger
Both the following tests will fail without further coding:
如果没有进一步编码,以下两个测试都将失败:
@Test
public void fail1() {
throw new NullPointerException("Will fail");
}
@Test
public void fail2() throw IOException {
throw new IOException("Will fail");
}
回答by Sergii Bishyr
Actually your test should fail when an exception in code is thrown. Of course, if you catch this exception and do not throw it (or any other exception) further, test won't know about it. In this case you need to check the result of method execution. Example test:
实际上,当抛出代码异常时,您的测试应该会失败。当然,如果你捕捉到这个异常并且不再抛出它(或任何其他异常),测试将不会知道它。在这种情况下,您需要检查方法执行的结果。示例测试:
@Test
public void test(){
testClass.test();
}
Method that will fail the test:
测试失败的方法:
public void test(){
throw new RuntimeException();
}
Method that will not fail the test
不会通过测试的方法
public void test(){
try{
throw new RuntimeException();
} catch(Exception e){
//log
}
}
回答by mcalmeida
In JUnit 4, you can explicitly assert that a @Test should fail with a given exception using the expected
property of the @Test
annotation:
在 JUnit 4 中,您可以使用注释的expected
属性显式断言 @Test 应该因给定的异常而失败@Test
:
@Test(expected = NullPointerException.class)
public void expectNPE {
String s = null;
s.toString();
}
See JUnit4 documentation on it.
请参阅有关它的 JUnit4 文档。