2

我正在尝试重构这个不使用的旧代码,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()ore.getResponse().getEntity(String.class)的值ExpectedException。我确实看到ExpectedException有一个需要 hamcrest的expectMatcher方法。也许这就是关键,但我不确定如何使用它。

如果该状态仅存在于具体异常上,我如何断言该异常处于我想要的状态?

4

1 回答 1

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));

    ....
}
于 2014-03-18T21:23:30.193 回答