2017-05-09 207 views
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(); 
} 

回答

0

你在做什麼基本上是:

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

這樣做會給你一個NullPointerException,因爲getAttribute(CONTROLLER_NAME)回報是零,而Optional.of(..)不接受空參數,而在原始代碼,您正在使用Strings.isEmpty(..)測試其值。

相關問題