参考:
http://junit-team.github.io/junit/javadoc/4.10/org/junit/rules/ExpectedException.html
http://stackoverflow.com/questions/4489801/junit-test-analysing-expected-exceptions
http://jakegoulding.com/blog/2012/09/26/be-careful-when-using-junit-expected-exceptions/
方法一:使用ExpectedException
发生以下情况时,会认为失败
- 没有抛出异常
- 抛出的异常类型不正确
- 抛出的异常的message不正确
package com.yasi.test;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class UnitTest {
@Rule
public ExpectedException thrown= ExpectedException.none();
@Test
public void test1() {
thrown.expect(NumberFormatException.class);
thrown.expectMessage("The first error");
throw new NumberFormatException("The first error");
}
@Test
public void test2() {
thrown.expect(IndexOutOfBoundsException.class);
thrown.expectMessage("The second error");
throw new IndexOutOfBoundsException("The second error");
}
}
注意:
这里使用的expect() 函数原型是
public void expectMessage(String substring)即, 传入的字符串不是要求 “刚好匹配”,而是, 只要 “被包含” 就算成功。
这里有个问题,thrown.expectMessage("The first error") 一行,如果期望的message内容写成 "a",总是成功,但写成 "aa" 就失败。还不知道是怎么回事……
方法二:使用junit.Assert.fail
发生以下情况时,会认为失败
- 没有抛出异常
- 抛出的异常类型不正确
这里也可以用assertEquals来判断抛出的异常的message是否正确
package com.yasi.test;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class UnitTest {
@Test
public void test3() {
try {
long data = Long.parseLong("???");
fail("NumberFormatException is not thrown as expected");
} catch (Exception e) {
assertTrue(e instanceof NumberFormatException);
}
}
}