0

I want to unit test my code below with Mockito, could anyone let me know how I can mock the response from the callback, which is anonymous in my code? Particularly, how can I verify if doSomethingOnResponse() gets called with the mocked response?

public void runTask() {
    Data data = null;

    ClassA objA = new ClassA(new Callback() {
         @Override
         public void onResponse(Response response) {
            data = getSomethingFromResponse(response);
         }
    };

    //this is a synchronous call     
    objA.run();

    doSomethingElse(data); //data gets assigned from the callback
}

Thanks a lot in advance!

Green Ho
  • 881
  • 3
  • 14
  • 27
  • Does your use-case match [this one](http://stackoverflow.com/q/13616547/1426891)? You're passing the Callback as a constructor argument rather than a method argument, but the answers are the same--use an ArgumentCaptor or an Answer. – Jeff Bowman Dec 17 '14 at 05:48
  • Yes, I have to pass the Callback to the constructor due to the design restriction, so if I mimic the use case you mentioned, how can I do the when part which is for a method call? – Green Ho Dec 17 '14 at 06:30
  • I don't really understand your question. Where is `onResponse` invoked? In your example code, you don't use the `response` argument at all - is that intentional? Perhaps a real-life (compilable) example would be helpful. – Duncan Jones Dec 17 '14 at 08:30
  • Sorry, I just missed the "response" in the doSomethingOnResponse(response), it does get used, and that's what I am trying to verify. – Green Ho Dec 17 '14 at 20:41
  • Could anyone please give me an example? Thanks! – Green Ho Dec 18 '14 at 00:06
  • Your question alludes to (1) some enclosing class, (2) ClassA, (3) Callback, (4) Response, and (5) Data. Which _unit_ are you trying to test? Where would `doSomethingElse` and `getSomethingFromResponse` be defined? – Jeff Bowman Dec 18 '14 at 05:55
  • Hi Jeff, getSomethingFromResponse(response) is a private method that parses the data from the raw response, I want to unit test if it gets invoked on getting the response from the callback. I also want to unit test if it parses the response correctly. Thanks! – Green Ho Dec 18 '14 at 18:25
  • I'd also want to unit test the runTask() as a whole. – Green Ho Dec 18 '14 at 18:37

0 Answers0