JMockit模拟类为子方法返回null

时间:2018-12-13 09:45:52

标签: unit-testing jmockit

我想测试一个从JAX-RS实现ContainerRequestFilter的过滤器。

实现类为:

public class CookieRequestFilter implements ContainerRequestFilter {

public static final String EXCLUDE_FROM_FILTER = ".*healthy$|.*alive$";

@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    URI uri = requestContext.getUriInfo().getAbsolutePath();
    if (uri.getPath().matches(EXCLUDE_FROM_FILTER)) {
        return;
    }
    Cookie cookie = requestContext.getCookies().get("cookie_identifier");
    // some other code here
}
}

使用JMockit框架运行单元测试。 测试是:

@RunWith(JMockit.class)
public class CookieRequestFilterTest {

@Tested
private CookieRequestFilter cookieRequestFilter;

@Test
public void filterCookie(@Mocked ContainerRequestContext request) throws IOException {
    Map<String, Cookie> cookies = new HashMap<>();
    String identifier = "1";
    cookies.put("cookie_identifier", getCookie(identifier));
    new Expectations() {{
        request.getCookies();
        times = 1;
        result = cookies;
    }};

    cookieRequestFilter.filter(request);
}

private NewCookie getCookie(String value) {
    return new NewCookie("cookie_identifier",
                         value,
                         "/",
                         "",
                         1,
                         null,
                         840,
                         new Date(new Date().getTime() + 840 * 1000),
                         true,
                         false);
}
}

它在

给了我NPE
  

uri.getPath()。matches(EXCLUDE_FROM_FILTER)

有人可以帮我吗?

0 个答案:

没有答案