2014-03-18 24 views
2

我試圖重構這個舊的代碼不使用ExpectedException使其使用它:如何使用JUnit的ExpectedException來檢查僅在子例外的狀態?

try { 
     //... 
     fail(); 
    } catch (UniformInterfaceException e) { 
     assertEquals(404, e.getResponse().getStatus()); 
     assertEquals("Could not find facility for aliasScope = DOESNTEXIST", e.getResponse().getEntity(String.class)); 
    } 

我無法弄清楚如何做到這一點,因爲我不知道如何在ExpectedException中檢查e.getResponse().getStatus()e.getResponse().getEntity(String.class)的值。我確實看到ExpectedException有一個expect方法需要一個hamcrest Matcher。也許這是關鍵,但我不確定如何使用它。

如何聲明異常處於我想要的狀態,如果該狀態只存在於具體的異常?

回答

3

「最佳」的方式就像是在此所述的自定義匹配:http://java.dzone.com/articles/testing-custom-exceptions

所以,你會想是這樣的:

import org.hamcrest.Description; 
import org.junit.internal.matchers.TypeSafeMatcher; 

public class UniformInterfaceExceptionMatcher extends TypeSafeMatcher<UniformInterfaceException> { 

public static UniformInterfaceExceptionMatcher hasStatus(int status) { 
    return new UniformInterfaceExceptionMatcher(status); 
} 

private int actualStatus, expectedStatus; 

private UniformInterfaceExceptionMatcher(int expectedStatus) { 
    this.expectedStatus = expectedStatus; 
} 

@Override 
public boolean matchesSafely(final UniformInterfaceException exception) { 
    actualStatus = exception.getResponse().getStatus(); 
    return expectedStatus == actualStatus; 
} 

@Override 
public void describeTo(Description description) { 
    description.appendValue(actualStatus) 
      .appendText(" was found instead of ") 
      .appendValue(expectedStatus); 
} 

}

然後在你的測試代碼:

@Test 
public void someMethodThatThrowsCustomException() { 
    expectedException.expect(UniformInterfaceException.class); 
    expectedException.expect(UniformInterfaceExceptionMatcher.hasStatus(404)); 

    .... 
} 
+0

這裏有很多編譯錯誤。但除此之外,這是有效的。如果我有第二個,你的'@ Test'的第一行真的有必要嗎? IE:我可以切出'expectedException.expect(UniformInterfaceException.class);'? –

+0

@tieTYT對不起,我做了一個非常快速和骯髒的寫在沒有在IDE中檢查它。現在所有固定,所以它編譯。它也看起來像你可以擺脫'expect(UniformInterfaceException.class)'我認爲hamcrest會捕獲任何異常(例如hamcrest試圖調用你的匹配器時的轉換異常)並將其視爲失敗。 – dkatzel