我有以下代码:
private SaveTransactionClient mockedTransactionClient;
private static Publisher publisher;
private static MyDTO mDTO1;
private static MyDTO mDTO2;
private static MyDTO mDTO3;
@BeforeClass
public void setUp() throws IOException {
TransactionResponse successResponse = new TransactionResponse();
successResponse.setDateRequest("2016-04-27 18:47:50");
successResponse.setResponse("OK");
successResponse.setTransactionNumber("1");
TransactionResponse failedResponse = new TransactionResponse();
failedResponse.setDateRequest("2016-04-27 18:47:50");
failedResponse.setResponse("Dublicate Transaction Error");
failedResponse.setTransactionNumber("1");
mDTO1 = new MyDTO(1, LocalDateTime.now(), 0);
mDTO2 = new MyDTO(2, LocalDateTime.now(), 0);
mDTO3 = new MyDTO(3, LocalDateTime.now(), 0);
mockedTransactionClient = mock(SaveTransactionClient.class);
when(mockedTransactionClient.sendTransactionRequest(mDTO1)).thenReturn(successResponse);
when(mockedTransactionClient.sendTransactionRequest(mDTO2)).thenReturn(failedResponse);
when(mockedTransactionClient.sendTransactionRequest(mDTO3)).thenThrow(new IOException());
when(mockedTransactionClient.sendTransactionRequest(any(MDTO.class))).thenThrow(new IOException());
publisher = new publisherImpl(mockedTransactionClient);
}
实际测试
@Test
public void TestOnlyExceptionalPublishing() {
BlockingQueue<MDTO> mDTOs = new LinkedBlockingQueue<>(Arrays.asList(mDTO3));
assertEquals(mDTOs.size(), 1);
List<MDTO> successful = publisher.publish(wDTOs);
assertEquals(successful.size(), 0);
}
@Test
public void TestOneSuccessContainsExceptionalPublishing() {
BlockingQueue<MDTO> mDTOs = new LinkedBlockingQueue<>(Arrays.asList(mDTO3,mDTO1, mDTO2));
assertEquals(mDTOs.size(), 3);
List<MDTO> successful = publisher.publish(mDTOs);
assertEquals(successful.size(), 1);
}
现在MDTO
是不可变的,publisher.publish(mDTO)
的工作方式是异常增加MDTO
中的“重试”计数器并重试最多3个倍。当计数器递增时,会生成一个新的MDTO
,当响应不被Mockito存根时,会给我带来问题。我添加了any
但是这使得其他测试失败,因为它抛出所有而不是除了我已经提供的对象之外的任何其他。
在Mockito中有没有 anyOther 类型的方法?
答案 0 :(得分:1)
我认为(如果我确实理解正确)您正在寻找doAnswer
/thenAnswer
:
when(mockedTransactionClient.sendTransactionRequest(any(MyDTO.class)).thenAnswer(new Answer<TransactionResponse>() {
@Override
public TransactionResponse answer(final InvocationOnMock invocation) {
final MyDTO arg = invocation.getArgumentAt(0, MyDTO.class)
// do stuff here based on arg
return someTransactionResponse; // or throw some exception
}
});