Java JUnit 测试预期异常的正确方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42374416/
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
JUnit right way of test expected exceptions
提问by Daniel Vega
Hello guys I was wondering if this way of testing my exception is ok, i have this exception i need to throw in the second test annotation, im receiving as result a red evil bar, and a succeed and a failure, as you can guess the failure is my concern, i have a fail(); there but the reason is because i read thats the way to test the exception and now im confused.
大家好,我想知道这种测试我的异常的方式是否可以,我有这个异常,我需要在第二个测试注释中抛出,结果我收到一个红色的邪恶条,以及成功和失败,你可以猜到失败是我的问题,我有一个失败();那里但原因是因为我读到那是测试异常的方法,现在我很困惑。
Also i have to say im willin get the green bar because im expecting the exception, but i dont know if failure is the right way to see the answer of the expected exception.
另外我不得不说我会得到绿色条,因为我期待异常,但我不知道失败是否是查看预期异常答案的正确方法。
Also if you had any advice, I would appreciate it
另外,如果您有任何建议,我将不胜感激
@Before
public void setUp() throws Exception {
LogPack.logPacConfig(Constants.LOGGING_FILE);
gtfri = "+RESP:GTFRI,380502,869606020101881,INCOFER-gv65,,10,1,1,0.0,0,888.1,-84.194560,9.955602,20170220074514,,,,,,0.0,,,,100,210100,,,,20170220074517,40A2$";
weirdProtocol = "+RESP:GRI,380502,869606020101881,INCOFER-gv65,,10,1,1,0.0,0,888.1,-84.194560,9.955602,20170220074514,,,,,,0.0,,,,100,210100,,,,20170220074517,40A2$";
factory = new LocomotiveFactory();
}
@Test
public void GTFRICreationTester_shouldPass() throws TramaConProtolocoloDesconocido {
assertTrue(factory.createLocomotive(gtfri, false, new Date()) instanceof LocomotiveGTFRI);
}
@Test(expected = TramaConProtolocoloDesconocido.class)
public void GTFRICreationTester_shouldFail() {
try {
factory.createLocomotive(weirdProtocol, false, new Date());
fail("Expected an TramaConProtolocoloDesconocido");
} catch (TramaConProtolocoloDesconocido e) {
//assertSame("exception thrown as expected", "no se conoce el protocolo dado para la creacion de este factory", e.getMessage());;
}
}
采纳答案by Sergii Bishyr
There is 3 most common ways to test expected exception:
有 3 种最常见的方法来测试预期的异常:
First one is the most common way, but you can test only the type of expected exception with it. This test will fail if ExceptionType
won't be thrown:
第一种是最常见的方式,但您只能使用它测试预期异常的类型。如果ExceptionType
不抛出此测试将失败:
@Test(expected = ExceptionType.class)
public void testSomething(){
sut.doSomething();
}
Also you cannot specify the failure message using this approach
您也不能使用此方法指定失败消息
The better option is to use ExpectedException JUnit @Rule. Here you can assert much more for expected exception
更好的选择是使用ExpectedException JUnit @Rule。在这里,您可以为预期的异常断言更多
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void testSomething(){
thrown.expect(ExceptionType.class);
thrown.expectMessage("Error message");
thrown.expectCause(is(new CauseOfExeption()));
thrown.reportMissingExceptionWithMessage("Exception expected");
//any other expectations
sut.doSomething();
}
The third option will allow you to do the same as with using ExpectedException @Rule, but all the assertion should be written manually. However the advantage of this method is that you can use any custom assertion and any assertion library that you want:
第三个选项将允许您执行与使用 ExpectedException @Rule 相同的操作,但应手动编写所有断言。但是,此方法的优点是您可以使用任何自定义断言和所需的任何断言库:
@Test
public void testSomething(){
try{
sut.doSomething();
fail("Expected exception");
} catch(ExceptionType e) {
//assert ExceptionType e
}
}
回答by Mouad EL Fakir
You don't need to catch the Exception
with try-catch
你并不需要赶上Exception
与try-catch
@Test(expected = TramaConProtolocoloDesconocido.class)
public void GTFRICreationTester_shouldFail() {
factory.createLocomotive(weirdProtocol, false, new Date());
}
If we suppose that factory.createLocomotive(weirdProtocol, false, new Date())
throws the exception
when you apply a scenario that makes the exception
thrown.
如果我们假设当您应用导致factory.createLocomotive(weirdProtocol, false, new Date())
抛出的exception
场景时exception
抛出。
void createLocomotive(param...) {
//something...
throw new TramaConProtolocoloDesconocido();
}
回答by Arpit Aggarwal
You can use ExpectedExceptionwhich can provide you more precise information about the exception expected to be thrown with the ability to verify error message, as follows:
您可以使用ExpectedException,它可以为您提供有关预期抛出的异常的更准确信息,并具有验证错误消息的能力,如下所示:
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
public class TestClass {
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test
public void GTFRICreationTester_shouldFail() {
expectedException.expect(TramaConProtolocoloDesconocido.class);
factory.createLocomotive(weirdProtocol, false, new Date());
}
}
To expolore more about it, you can refer to the blog written by me here - Expected Exception Rule and Mocking Static Methods – JUnit
要深入了解它,你可以参考我在这里写的博客——预期异常规则和模拟静态方法——JUnit
回答by pezetem
if your are using java 8, I would recommend to go for the AssertJ library
如果您使用的是 java 8,我建议您使用 AssertJ 库
public void GTFRICreationTester_shouldFail() {
assertThatExceptionOfType(EXCEPTION_CLASS).isThrownBy(() -> { factory.createLocomotive(weirdProtocol, false, new Date()) })
.withMessage("MESSAGE")
.withMessageContaining("MESSAGE_CONTAINING")
.withNoCause();
}
with that solution you can at one verify exception type, with message etc.
使用该解决方案,您可以同时验证异常类型、消息等。
for more reading, take a look at: http://joel-costigliola.github.io/assertj/assertj-core-features-highlight.html#exception-assertion
如需更多阅读,请查看:http: //joel-costigliola.github.io/assertj/assertj-core-features-highlight.html#exception-assertion