'doAnswer and ClassCastException

I'm trying to stub a method invocation

SpotApi.APIlistCandlesticksRequest req = spotApi.listCandlesticks(coinPair);

to return different values for different invocations, with:

  @Mock private SpotApi.APIlistCandlesticksRequest 
  mockAPIlistCandlesticksRequest, mockAPIlistCandlesticksRequest2;
  . . . 
   doAnswer(inv-> new Answer<SpotApi.APIlistCandlesticksRequest>() {
  private int count = 0;
  @Override
  public SpotApi.APIlistCandlesticksRequest answer(InvocationOnMock invocationOnMock) {
    count++;
    if (count == 1) {
      return mockAPIlistCandlesticksRequest;
    } else if (count == 2) {
      return mockAPIlistCandlesticksRequest2;
    }
    return null;
  }
}).when(mockSpotApi).listCandlesticks(COINPAIR);

but it fails with

: class com.gateiobot.macd.MACDCalculationTest$1 cannot be cast to class io.gate.gateapi.api.SpotApi$APIlistCandlesticksRequest (com.gateiobot.macd.MACDCalculationTest$1 and io.gate.gateapi.api.SpotApi$APIlistCandlesticksRequest are in unnamed module of loader 'app')

Any help is much appreciated.



Solution 1:[1]

The problem is that you are making an Answer which returns an answer which returns the SpotApi.APIlistCandlesticksRequest. You see, the construct inv -> new Answer() { ...} is a function returning an Answer. When given as argument to doAnswer it implicitly becomes an implementation of the Answer functional interface, per the contract of doAnswer.

Just keep one. If you keep the labda it will be more awkward to keep state (the count), so you can just keep the inner class:

doAnswer(new Answer<SpotApi.APIlistCandlesticksRequest>() { // NO inv ->
  private int count = 0;
  @Override
  public SpotApi.APIlistCandlesticksRequest answer(InvocationOnMock invocationOnMock) {
    count++;
    if (count == 1) {
      return mockAPIlistCandlesticksRequest;
    } else if (count == 2) {
      return mockAPIlistCandlesticksRequest2;
    }
    return null;
  }
}).when(mockSpotApi).listCandlesticks(COINPAIR);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nikos Paraskevopoulos