我正在为解析字符串的构造函数编写 jUnit 测试,然后检查许多内容。当有错误的数据时,对于每件事,都会抛出一些带有不同消息的 IllegalArgumentException。 所以我想为它编写测试,但我如何识别抛出的错误? 这是我该怎么做:
@Test(expected=IllegalArgumentException.class)
public void testRodneCisloRok(){
new RodneCislo("891415",dopocitej("891415"));
}
这就是我想要的样子,但我不知道是否有可能以某种方式写出来:
@Test(expected=IllegalArgumentException.class("error1"))
public void testRodneCisloRok(){
new RodneCislo("891415",dopocitej("891415"));
}
最佳答案
如果您有 JUnit 4.7 或更高版本,您可以使用这种(优雅的)方式:
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void testRodneCisloRok(){
exception.expect(IllegalArgumentException.class);
exception.expectMessage("error1");
new RodneCislo("891415",dopocitej("891415"));
}
关于java - 不同情况下的jUnit相同异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2444062/