Ich schreibe Test für RequestContextHolder
. Ich habe die Tests bestanden, aber nach dem Refaktorieren habe ich NullPointerException bekommen, kann aber nicht herausfinden warum.Java Spring RequestContext-Test löst NullPointerException sogar mit MockHttpServletRequest
Hier ist der Code.
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;
Und hier ist meine Tests
@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);
}
Dann Refactoring ich ein Motto sein, aber ich habe stattdessen Nullpointer.
public String processorName() {
return Optional.of(((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest().getAttribute(CONTROLLER_NAME)).orElse("<UNKNOWN>".intern()).toString();
}