我试图重构这个不使用ExpectedException
的旧代码,以便它 使用它:
try {
//...
fail();
} catch (UniformInterfaceException e) {
assertEquals(404, e.getResponse().getStatus());
assertEquals("Could not find facility for aliasScope = DOESNTEXIST", e.getResponse().getEntity(String.class));
}
我无法弄清楚如何执行此操作,因为我不知道如何检查e.getResponse().getStatus()
中e.getResponse().getEntity(String.class)
或ExpectedException
的值。我确实看到ExpectedException
有一个expect方法,需要一个hamcrest Matcher
。也许这是关键,但我不确定如何使用它。
如果该状态仅存在于具体异常上,我如何断言异常处于我想要的状态?
答案 0 :(得分: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));
....
}