Skip to content

Commit 6280541

Browse files
committed
add->how-do-you-assert-that-a-certain-exception-is-thrown-in-junit-4-tests.md
1 parent 8561923 commit 6280541

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
## JUnit如何断言一个确定的异常抛出
2+
3+
#### 问题
4+
5+
在JUnit4单元测试中,我要怎样做才能测试出有特定的异常抛出?我能想到的就只有下面的方法:
6+
7+
```java
8+
@Test
9+
public void testFooThrowsIndexOutOfBoundsException() {
10+
boolean thrown = false;
11+
12+
try {
13+
foo.doStuff();
14+
} catch (IndexOutOfBoundsException e) {
15+
thrown = true;
16+
}
17+
18+
assertTrue(thrown);
19+
}
20+
```
21+
22+
#### 回答1
23+
24+
在JUnit4后支持下面的写法:
25+
```java
26+
@Test(expected=IndexOutOfBoundsException.class)
27+
public void testIndexOutOfBoundsException() {
28+
ArrayList emptyList = new ArrayList();
29+
Object o = emptyList.get(0);
30+
}
31+
```
32+
(译者:在`@Test`注解内提供了`expected`属性,你可以用它来指定一个`Throwble`类型,如果方法调用中抛出了这个异常,那么这条测试用例就相当于通过了)
33+
34+
#### 回答2
35+
36+
如果你使用的是JUnit4.7,你可以使用如下的期望异常规则来验证异常信息:
37+
38+
```java
39+
public class FooTest {
40+
@Rule
41+
public final ExpectedException exception = ExpectedException.none();
42+
43+
@Test
44+
public void doStuffThrowsIndexOutOfBoundsException() {
45+
Foo foo = new Foo();
46+
47+
exception.expect(IndexOutOfBoundsException.class);
48+
foo.doStuff();
49+
}
50+
}
51+
```
52+
53+
这种方式比`@Test(expected=IndexOutOfBoundsException.class)`要更好,如果是在调用`foo.doStuff()`方法之前就已经抛出异常的话,测试结果就不是我们想要的了。
54+
(译者:同时,`ExpectedException`还能够验证异常信息,如`exception.expectMessage("there is an exception!");`
55+
56+
#### 拓展阅读
57+
58+
1. [JUnit:使用ExpectedException进行异常测试](http://www.tuicool.com/articles/ANviIz)
59+
2. [JUnit4 用法详解](http://www.blogjava.net/jnbzwm/archive/2010/12/15/340801.html)
60+
61+
#### StackOverflow地址:
62+
63+
[http://stackoverflow.com/questions/156503/how-do-you-assert-that-a-certain-exception-is-thrown-in-junit-4-tests](http://stackoverflow.com/questions/156503/how-do-you-assert-that-a-certain-exception-is-thrown-in-junit-4-tests)

0 commit comments

Comments
 (0)