2012-03-28 75 views
3

我正在创建一个测试HTTP相互作用的通用模拟客户端。为此,我希望能够用同样的方法做出许多回应。 与正常的模拟,这将不会是一个问题:嘲笑部分模拟与Mockito连续响应的通用数

when(mock.execute(any(), any(), any())).thenReturn(firstResponse, otherResponses) 

不过,我使用的是部分模拟,在这里我只是想嘲笑方法使HTTP请求,因为可能没有进入到现场在单元测试执行的上下文中,对于这个问题,通常是终点或因特网。

所以我会做这样的事情:

doReturn(response).when(spy).execute(hostCaptor.capture(), requestCaptor.capture(), contextCaptor.capture()); 

不过,我想能够支持多个响应(没有太多的“互动”的)。但是没有任何一种方法,一次只能得到一个以上的答案。

我一个解决方案的首次尝试是反复地做到这一点:

Stubber stubber = null; 
for (HttpResponse response : responses) { 
    if (stubber == null) { 
     stubber = doReturn(response); 
    } else { 
     stubber = stubber.doReturn(response); 
    } 
} 
stubber.when(spy).execute(hostCaptor.capture(), requestCaptor.capture(), contextCaptor.capture()); 

这并不能然而,以验证运行测试时(“未完成的磕碰检测”)。

所以 - 有没有办法用Mockito实现这一点?

感谢您的阅读。

回答

3

你可以写

doReturn(1).doReturn(2).doReturn(3).when(myMock).myMethod(any(), any(), any()); 

编辑:

如果你想要的值是数组myArray中,那么你也可以使用

import static java.util.Arrays.asList; 
import static org.mockito.Mockito.doAnswer; 
import org.mockito.stubbing.answers.ReturnElementsOf 

.... 

doAnswer(new ReturnsElementsOf(asList(myArray))) 
    .when(myMock).myMethod(any(), any(), any()); 
+0

谢谢您回答大卫,但我的问题是,我通常不知道r的数量响应,因为它是一个数组(或可变参数)。 – tveon 2012-03-29 07:56:27

+0

@tveon好的,看我的编辑如何处理这种情况。 – 2012-03-29 08:29:37

+0

这看起来正是我在找的东西。 :) – tveon 2012-03-29 13:29:33

1

我发现的解决方案是使用doAnswer来返回数组中的下一个响应。

Answer<HttpResponse> answer = new Answer<HttpResponse>() { 

    HttpResponse[] answers = responses; 
    int number = 0; 

    @Override 
    public HttpResponse answer(InvocationOnMock invocation) throws Throwable { 
     HttpResponse result = null; 
     if (number <= answers.length) { 
      result = answers[number]; 
      number++; 
     } else { 
      throw new IllegalStateException("No more answers"); 
     } 
     return result; 
    } 
}; 
doAnswer(answer).when(spy).execute(hostCaptor.capture(), requestCaptor.capture(), contextCaptor.capture());