j在不同情况下使用相同的异常 [英] jUnit same exception in different cases
问题描述
我正在为一个解析String的构造函数编写一个jUnit测试,然后检查很多东西。当有错误的数据时,对于每一件事,都会抛出一些带有不同消息的IllegalArgumentException。
所以我想为它编写测试,但是我如何识别抛出的错误?
这是我该怎么做的:
I'm writing a jUnit test for a constructor that parses a String and then check numerous things. When there's wrong data, for every thing, some IllegalArgumentException with different message is thrown. So I would like to write tests for it, but how can i recognize what error was thrown? This is how can I do it:
@Test(expected=IllegalArgumentException.class)
public void testRodneCisloRok(){
new RodneCislo("891415",dopocitej("891415"));
}
这就是我想要的,但我不知道如果有可能以某种方式写它:
and this is how I would like to be, but I don't know if it is possible to write it somehow:
@Test(expected=IllegalArgumentException.class("error1"))
public void testRodneCisloRok(){
new RodneCislo("891415",dopocitej("891415"));
}
推荐答案
你需要做的它是老式的方式:
You'll need to do it the old fashioned way:
@Test
public void testRodneCisloRok() {
try {
new RodneCislo("891415",dopocitej("891415"));
fail("expected an exception");
} catch (IllegalArgumentException ex) {
assertEquals("error1", ex.getMessage());
}
}
@Test(预期= ...)
语法是一种方便的方便,但在很多情况下它太简单了。
The @Test(expected=...)
syntax is a handy convenience, but it's too simple in many cases.
如果区分异常条件很重要,您可能需要考虑开发一个可以特定捕获的异常的类层次结构。在这种情况下, IllegalArgumentException
的子类可能是个好主意。它可以说是更好的设计,你的测试可以捕获特定的异常类型。
If it is important to distinguish between exception conditions, you might want to consider developing a class hierarchy of exceptions, that can be caught specifically. In this case, a subclass of IllegalArgumentException
might be a good idea. It's arguably better design, and your test can catch that specific exception type.
这篇关于j在不同情况下使用相同的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!