2016-12-10 125 views
1

方法調用我有使用的Mockito單元測試以下問題:如何嘲笑使用的Mockito

我有這樣的方法:

@Override 
public void handle(HttpExchange httpRequest) throws IOException { 
    Object[] outputResult = processRequest(httpRequest); 
    String response = (String) outputResult[0]; 
    Integer responseCode = (Integer) outputResult[1]; 
    httpRequest.sendResponseHeaders(responseCode, response.length()); 
    OutputStream os = httpRequest.getResponseBody(); 
    os.write(response.getBytes()); 
    os.close(); 
} 

我只想測試這種方法,而不是processRequestMethod這是內部調用的(我想在anthoer測試中單獨測試),所以我需要嘲笑它並在測試結束時檢查方法寫和關閉OutputStream類已被調用。

我已經嘗試了兩種方式,但沒有人沒有運氣:

@Test 
public void handleTest() throws IOException { 
    RequestHandler requestHandler=mock(RequestHandler.class); 
    String response = "Bad request"; 
    int responseCode = HttpURLConnection.HTTP_BAD_REQUEST; 
    Object[] result={response,responseCode}; 
    when(requestHandler.processRequest(anyObject())).thenReturn(result); 
    when (httpExchange.getResponseBody()).thenReturn(outputStream); 
    requestHandler.handle(httpExchange); 
    Mockito.verify(outputStream,times(1)).write(anyByte()); 
    Mockito.verify(outputStream,times(1)).close(); 
} 

通過上面的代碼中,processRequest方法不叫,但也不是說我想測試手柄的方法,所以測試失敗:

Mockito.verify(outputStream,times(1)).write(anyByte()); 

說這個方法根本沒有被調用。

但是如果我添加參數CALL_REAL_METHODS創建模擬,像這樣的時候:

@Test 
public void handleTest() throws IOException { 
    RequestHandler requestHandler=mock(RequestHandler.class,CALLS_REAL_METHODS); 
    String response = "Bad request"; 
    int responseCode = HttpURLConnection.HTTP_BAD_REQUEST; 
    Object[] result={response,responseCode}; 
    when(requestHandler.processRequest(anyObject())).thenReturn(result); 
    when (httpExchange.getResponseBody()).thenReturn(outputStream); 
    requestHandler.handle(httpExchange); 
    Mockito.verify(outputStream,times(1)).write(anyByte()); 
    Mockito.verify(outputStream,times(1)).close(); 
} 

然後processRequest的方法,我想跳過實際上是調用方法時執行該行:

when(requestHandler.processRequest(anyObject())).thenReturn(result); 

任何可能出錯的線索?

回答

3
在您的測試,而不是

RequestHandler requestHandler=mock(RequestHandler.class,CALLS_REAL_METHODS); 

使用Mockito.spy()

 RequestHandler requestHandler=spy(RequestHandler.class); 
     doReturn(result).when(requestHandler).processRequest(httpRequest); 

您可能希望doReturn().when()形式而非when().thenReturn()因爲第一次做執行方法而後者確實如此。


在另一方面,我寧願移動processRequest()另一個類,你可以注入的實例爲RequestHandler這將使更多的嘲諷......直

+0

不知道間諜。它像一個魅力。謝謝! – fgonzalez