jeudi 24 mars 2016

How to mock this callback using Mockito?

I have this production code in my Presenter:

@UiThread
public void tryToReplaceLogo(String emailInitiallySearchedFor, String logoUrl) {
    if(isTheEmailWeAskedApiForStillTheSameAsInTheInputField(emailInitiallySearchedFor)){
        if (!TextUtils.isEmpty(logoUrl)) {
            downloadAndShowImage(logoUrl);
        } else {
            view.displayDefaultLogo();
        }
    }
}

public void downloadAndShowImage(String url) {

    final Target target = new Target() {

        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
            view.displayLogoFromBitmap(bitmap);
        }

        @Override
        public void onBitmapFailed(Drawable errorDrawable) {

        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {

        }
    };

    Picasso.with(view.getViewContext()).load(url).resize(150, 150).centerInside().into(target);
}

And this unit test for it:

@Test
public void testDisplayLogoIfValidUrlReturnedAndEmailEnteredIsTheSame() throws Exception {
    when(loginView.getUserName()).thenReturn(VALID_EMAIL);
    when(loginView.getViewContext()).thenReturn(context);
    loginLogoFetcherPresenter.onValidateEmailEvent(createSuccessfulValidateEmailEvent(VALID_EMAIL));
    waitForAsyncTaskToKickIn();
    verify(loginView).displayLogoFromBitmap((Bitmap) anyObject());
}

However, the displayLogoFromBitmap method is never called so my test fails. I need to mock the Target dependency to invoke the onBitmapLoaded method but I don't know how.

Possibly I need to create a static inner class that implements Target so that I can set a Mocked implementation of that in my tests, but how do I invoke the onBitmapLoaded method on the mock?

Aucun commentaire:

Enregistrer un commentaire