0
我正在爲RequestContextHolder
編寫測試。我得到了測試通過,但後重構我得到NullPointerException但無法弄清楚爲什麼。Java Spring RequestContext測試即使使用MockHttpServletRequest也會拋出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();
}