即使使用MockHttpServletRequest,Java Spring RequestContext测试也会抛出NullPointerException

时间:2017-05-09 14:37:10

标签: java spring nullpointerexception guava

我正在为RequestContextHolder编写测试。我通过了测试但是在重构后我得到了NullPointerException,但无法弄清楚原因。

这是代码。

    String processorName = "<UNKNOWN>".intern();
    Optional<HttpServletRequest> request = Optional.of(((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest());
    String procName = (String) request.get().getAttribute(CONTROLLER_NAME);

    if (!Strings.isEmpty(procName)) {
        processorName = procName;
    }

    return processorName;

这是我的测试

@Test
public void testProcessorName() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setAttribute(CONTROLLER_NAME, "default");
    RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));

    String processorName = halUtils.processorName();
    assertEquals("default", processorName);
}

@Test
public void testProcessorNameWithoutAttribute() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));

    String processorName = halUtils.processorName();
    assertEquals("<UNKNOWN>", processorName);
}

@Test
public void testProcessorNameWithoutRequest() throws Exception {
    String processorName = halUtils.processorName();
    assertEquals("<UNKNOWN>", processorName);
}

然后我重构为一个班轮,但我得到了NullPointerException。

public String processorName() {
    return Optional.of(((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest().getAttribute(CONTROLLER_NAME)).orElse("<UNKNOWN>".intern()).toString();
}

1 个答案:

答案 0 :(得分:0)

你在做什么基本上是:

return Optional.of(null).orElse("<UNKNOWN>".intern()).toString();

这样做会给你一个NullPointerException,因为getAttribute(CONTROLLER_NAME)的返回值为null,Optional.of(..)不接受空参数,而在原始代码中,你用{{1}测试它的值}}