如何使用JUnit的ExpectedException检查仅在子Exception上的状态? [英] How can I use JUnit's ExpectedException to check the state that's only on a child Exception?

查看:77
本文介绍了如何使用JUnit的ExpectedException检查仅在子Exception上的状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试重构不使用ExpectedException的旧代码,以便它确实使用它:

I'm trying to refactor this old code that does not use ExpectedException so that it does use it:

    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具有

And I can't figure out how to do this because I don't know how to check the value of e.getResponse().getStatus() or e.getResponse().getEntity(String.class) in an ExpectedException. I do see that ExpectedException has an expect method that takes a hamcrest Matcher. Maybe that's the key, but I'm not exactly sure how to use it.

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

How do I assert that the exception is in the state I want if that state only exists on the concrete exception?

推荐答案

最佳"方式是一种自定义匹配器,例如此处所述:

The "best" way is a custom matcher like the ones described here: http://java.dzone.com/articles/testing-custom-exceptions

所以您想要这样的东西:

So you would want something like this:

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

}

然后在您的测试代码中:

then in your Test code:

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

    ....
}

这篇关于如何使用JUnit的ExpectedException检查仅在子Exception上的状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆