Why does mockito think my service is being called twice?

Kaigo :

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

  • Firstly, there should only be 1 call.

  • Secondly, when I check for 2 times verify(squareClient, times(2)).getPayment("p1") I get a null pointer because getPaymentsApi() is now null. Is this because the mock when() is not applying the second time?

Tom Cools :

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()".

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=378503&siteId=1