jUnit不同情况下相同的异常
我正在为构造函数编写 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"));
}
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"));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您有 JUnit 4.7 或更高版本,您可以使用这种(优雅的)方式:
If you have JUnit 4.7 or above you can use this (elegant) way:
您需要以老式的方式进行操作:
@Test(expected=...)
语法很方便,但在许多情况下过于简单。如果区分异常条件很重要,您可能需要考虑开发可以专门捕获的异常类层次结构。在这种情况下,
IllegalArgumentException
的子类可能是一个好主意。这可以说是更好的设计,并且您的测试可以捕获特定的异常类型。You'll need to do it the old fashioned way:
The
@Test(expected=...)
syntax is a handy convenience, but it's too simple in many cases.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.