2017-05-09 8 views
0

RequestContextHolder에 대한 테스트를 작성하고 있습니다. 테스트가 통과되었지만 리팩터링 한 후에 NullPointerException이 발생했지만 이유를 파악할 수 없습니다.Java Spring RequestContext 테스트에서 MockHttpServletRequest를 사용하는 경우에도 NullPointerException이 throw됩니다.

다음은 코드입니다.

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; 

그리고 여기 그때 내가 한 라이너로 리팩토링하지만 대신에 NullPointerException이있어 내 테스트

@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); 
} 

입니다.

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

답변

0

당신이하고있는 것은 기본적으로 : getAttribute(CONTROLLER_NAME)의 반환이 null이기 때문에 이렇게

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

, 당신에게 NullPointerException이 제공되며, Optional.of(..)가 null 매개 변수를 허용하지 않는 원래의 코드에있는 동안 , 당신은 그 값을 Strings.isEmpty(..)으로 테스트하고있었습니다.