說來慚愧,雖然之前已經看過junit的源碼了,也寫了幾篇部落格,但是長時間不寫test case,今天想要寫抛exception相關的test case時,竟然不知道怎麼寫了。。。。。好記性不如爛筆頭,記下來先~~
對于使用驗證test case方法中抛出的異常,我起初想到的是一種比較簡單的方法,但是顯得比較繁瑣:
@test
public void testoldstyle() {
try {
double value = math.random();
if(value < 0.5) {
throw new illegalstateexception("test");
}
assert.fail("expect illegalstateexception");
} catch(illegalstateexception e) {
}
}
google了一下,找到另外幾種更加友善的方法:1,使用test注解中的expected字段判斷抛出異常的類型。2,使用expectedexception的rule注解。
個人偏好用test注解中的expected字段,它先的更加簡潔,不管讀起來還是寫起來都很友善,并且一目了然:
@test(expected = illegalstateexception.class)
public void testthrowexception() {
throw new illegalstateexception("test");
public void testnotthrowexception() {
system.out.println("no exception throws");
對rule注解的使用(隻有在junit4.7以後才有這個功能),它提供了更加強大的功能,它可以同時檢查異常類型以及異常消息内容,這些内容可以隻包含其中的某些字元,expectedexception還支援使用hamcrest中的matcher,預設使用isinstanceof和stringcontains matcher。在blockjunit4classrunner的實作中,每一個test case運作時都會重新建立test class的執行個體,因而在使用expectedexception這個rule時,不用擔心在多個test case之間互相影響的問題:
@rule
public final expectedexception expectedexception = expectedexception.none();
public void testthrowexceptionwithrule() {
expectedexception.expect(illegalstateexception.class);
public void testthrowexceptionandmessagewithrule() {
expectedexception.expectmessage("fail");
throw new illegalstateexception("expect fail");