我正在为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();
}
答案 0 :(得分:0)
你在做什么基本上是:
return Optional.of(null).orElse("<UNKNOWN>".intern()).toString();
这样做会给你一个NullPointerException,因为getAttribute(CONTROLLER_NAME)
的返回值为null,Optional.of(..)
不接受空参数,而在原始代码中,你用{{1}测试它的值}}