2016-12-10 96 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