Mockito 返回特定对象的值,并为相同类型的所有其他对象抛出



我有下面的代码:

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)的工作方式是,在 Exception 上,MDTO递增"重试"计数器,最多重试 3 次。当计数器递增时,会生成一个新的MDTO,并且响应不会被 Mockito 存根,这给我带来了问题。我添加了any但这会使其他测试失败,因为它会抛出除我已经提供的对象之外的所有测试,而不是任何其他测试。

在Mockito中还有其他方法可以做到这一点吗?

我认为

(如果我理解正确的话)您正在寻找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
   }
});

相关内容

  • 没有找到相关文章

最新更新