JUnit测试Java代码中的异常有3种方式
public class Fruit {
private String name;
private int size;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSize() {
return size;
}
public void setSize(int size) {
if (size < 0 ) {
throw new IllegalArgumentException("size is invalid");
}
this.size = size;
}
}
1、测试setSize方法
try-catch 方式
@Test
public void getExceptionWhenSizeLessThanZero() {
Fruit fruit = new Fruit();
try {
fruit.setSize(-1);
fail("should get IllegalArgumentException");
} catch (IllegalArgumentException ex) {
assertThat(ex.getMessage(),containsString("size is invalid"));
}
}
JUnit annotation方式
JUnit中提供了一个expected的annotation来检查异常。
@Test(expected = IllegalArgumentException.class)
public void getExceptionWhenSizeLessThanZero() {
Fruit fruit = new Fruit();
fruit.setSize(-1);
}
简洁多了,但是无法检查异常中的消息。
ExpectedException rule
JUnit7以后提供了一个叫做ExpectedException的Rule来实现对异常的测试。
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void getExceptionWhenSizeLessThanZero() {
Fruit fruit = new Fruit();
exception.expect(IllegalArgumentException.class);
exception.expectMessage(containsString("size is invalid"));
fruit.setSize(-1);
}
这种方式既可以检查异常类型,也可以验证异常中的消息。
使用catch-exception库
首先引用该库
pom.xml
<dependency>
<groupId>com.googlecode.catch-exception</groupId>
<artifactId>catch-exception</artifactId>
<version>1.2.0</version>
<scope>test</scope> <!-- test scope to use it only in tests -->
</dependency>
@Test
public void getExceptionWhenSizeLessThanZero() {
Fruit fruit = new Fruit();
catchException(fruit).setSize(-1);
assertThat(caughtException(),instanceOf(IllegalArgumentException.class));
assertThat(caughtException().getMessage(), containsString("size is invalid"));
}
可以精准的验证异常是被测方法抛出来的,而不是其它方法抛出来的。
catch-exception库还提供了多种API来进行测试
先加载fest-assertion库。
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert-core</artifactId>
<version>2.0M10</version>
</dependency>
@Test
public void getExceptionWhenSizeLessThanZero() {
// given
Fruit fruit = new Fruit();
// when
when(fruit).setSize(-1);
// then
then(caughtException())
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("size is invalid")
.hasNoCause();
}
或者
@Test
public void getExceptionWhenSizeLessThanZero() {
// given
Fruit fruit = new Fruit();
// when
when(fruit).setAge(-1);
// then
assertThat(caughtException(), allOf(
instanceOf(IllegalArgumentException.class)
, hasMessage("size is invalid")
,hasNoCause()));
}