jeudi 31 mars 2016

Android Unit Test: How to mock a listener that is sent as argument to an asynchronous method?

I have a method that receives a listener (interface) with onSuccess(result) and onFail(error) methods.
The tested method performs some actions (on another thread) and eventually calls the listener with an answer.

Example code for the method itself (not the test):

testedObject.performAsyncAction("some data", new IListener(){
    @Override
    public void onSuccess(int result) {
        if (result == 1) { /* do something */ }
        else if (result == 2) { /* do something else */ }
    }

    @Override
    public void onFailure(Error error) {
        if (error.getMessage().equals("some error")) { /* do something */ }
        else if (error.getMessage().equals("another error")) { /* do something else */ }
    }
});

I want to have few tests on this method:

  • Success when onSuccess(1) is called
  • Success when onSuccess(2) is called
  • Success when onFailure(new Error("some error")) is called
  • Success when onFailure(new Error("another error")) is called

Thank you!

Aucun commentaire:

Enregistrer un commentaire