javamockitosquare-connectsquare

Why does mockito think my service is being called twice?


I’m having trouble using mockito to verify the number of calls to a mocked method.

This is my test

@Mock
private SquareClient squareClient;

@Mock
private PaymentsApi paymentsApi;


@Test
public void testBlah() throws Exception {
    ...
    when(squareClient.getPaymentsApi().getPayment("p1")).thenReturn(VALID_PAYMENT_RESPONSE);

    sut.process(EXAMPLE_PAYLOAD);

    verify(squareClient).getPaymentsApi().getPayment("p1");     //<--------------error here
}

This is my setup method

@Before
public void setup() {
    ...
    when(squareClient.getPaymentsApi()).thenReturn(paymentsApi);
    ...
}

Error

Wanted 1 time: at com.squareup.square.SquareClient.getPaymentsApi(SquareClient.java:239) But was 2 times:

That’s seems fine, but when you see the two calls come from. . one is in the service,

Payment payment = squareClient.getPaymentsApi().getPayment(paymentId).getPayment();

And one in the test. Why is this one here?

when(squareClient.getPaymentsApi().getPayment("p1")).thenReturn(VALID_PAYMENT_RESPONSE);

My issues


Solution

  • Apply your when() statement in your @Test directly on the PaymentsApi object.

    when(paymentsApi.getPayment("p1")).thenReturn(VALID_PAYMENT_RESPONSE);
    

    You can't chain your method calls when using "when()".