Java 如何使用JUnit';s ExpectedException检查';只有孩子例外吗?
我正在尝试重构这个不使用Java 如何使用JUnit';s ExpectedException检查';只有孩子例外吗?,java,junit,expected-exception,Java,Junit,Expected Exception,我正在尝试重构这个不使用ExpectedException的旧代码,以便它使用它: 我不知道怎么做,因为我不知道如何检查e.getResponse().getStatus()或e.getResponse().getEntity(String.class)中的ExpectedException的值。我确实看到,ExpectedException有一个方法,它采用hamcrest匹配器。也许这是关键,但我不确定如何使用它 如果该状态仅存在于具体异常上,我如何断言该异常处于我想要的状态?最好的方法是使
ExpectedException
的旧代码,以便它使用它:
我不知道怎么做,因为我不知道如何检查e.getResponse().getStatus()
或e.getResponse().getEntity(String.class)
中的ExpectedException
的值。我确实看到,ExpectedException
有一个方法,它采用hamcrest匹配器。也许这是关键,但我不确定如何使用它
如果该状态仅存在于具体异常上,我如何断言该异常处于我想要的状态?最好的方法是使用如下所述的自定义匹配器:
所以你会想要这样的东西:
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);
}
这里面有很多编译错误。但除此之外,这是可行的。如果我有第二行,你的@测试的第一行是否真的有必要?IE:expectedException.expect(UniformInterfaceException.class)是否可以删除expectedException.expect代码>?@tiety对不起,我没有在IDE中检查它,就写了一篇非常快速而肮脏的文章。现在全部修复,因此可以编译。看起来您还可以摆脱expect(UniformInterfaceException.class)
我认为hamcrest将捕获任何异常(如hamcrest尝试调用匹配器时的强制转换异常),并将其视为失败。
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));
....
}