junit 4中对指定异常的测试
2013-07-01 18:05
218 查看
junit 4中,也可以测试指定的异常是否出现了,比如:
要测试是否IllegalArgumentException抛出了,则可以使用注解的annotation:
但很奇怪,居然不能这样:
public class Person { private final String name; private final int age; public Person(String name, int age) { this.name = name; this.age = age; if (age <= 0) { throw new IllegalArgumentException('Invalid age:' + age); } } }
要测试是否IllegalArgumentException抛出了,则可以使用注解的annotation:
import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class PersonTest { @Rule public ExpectedException exception = ExpectedException.none(); @Test public void testExpectedException() { exception.expect(IllegalArgumentException.class); exception.expectMessage(containsString('Invalid age')); new Person('Joe', -1); } }
但很奇怪,居然不能这样:
@Test(expected = IllegalArgumentException.class) public void testExpectedException2() { new Person('Joe', -1); }
相关文章推荐
- spring环境下的JUnit4测试异常记录
- Junit测试spring hibernate产生javaw.exe异常的问题解决
- JUnit 4 如何正确测试异常
- JUnit 4 如何正确测试异常
- 使用JUnit测试预期异常
- Junit测试出现异常:Exception in thread "main" java.lang.NoSuchMethodError: org.junit.runner.Description.cre
- 没有测试符合【junit异常】
- 用Junit测试出现映射注解异常
- 使用JUnit测试预期异常
- 在使用Microsoft Visual Studio Test Controller 2010进行测试时,报如下错误: System.DllNotFoundException: 无法加载 DLL“Microsoft.VisualStudio.QualityTools.RecorderBarBHO100.dll”: 找不到指定的模块。 (异常来自 HRESULT:0x8007007E)。
- Junit 小案例 测试异常
- glog测试时链接异常:LNK4042: 对象被多次指定;已忽略多余的指定(VS2010)
- JUnit - 怎么测试异常
- junit 异常测试
- junit 使用JUnit测试预期异常
- Junit指定运行的测试方法
- Java中的异常测试框架JUnit使用上手指南
- Junit测试出现空指针异常
- JUnit中测试异常抛出的方法
- 如何在junit中判断指定异常的抛出