mercredi 29 avril 2020

Mock method failure - Java

I have the following piece of code:

void startLogin() {
        if (userNotLoggedIn) {
            view.showLoginScreen(loginInterface);
        } else {
            refreshToken();
        }
    }

void refreshToken() {
            authController.refreshToken( new ResultListener() {
                @Override
                public void onSuccess() {
                    Log.d(TAG, "Token refreshed successfully");
                    view.showApp();
                }

                @Override
                public void onError(AuthControllerException exception) {
                    Log.w(TAG, "Token refresh failed", exception);
                    view.showLoginScreen(loginInterface);
                }
            });
    }

I wanna test the method above with the three following tests, of which the first one is already working:

@Test
    public void startLogin_RefreshToken_WhenLoggedIn() {
        givenUserIsLoggedIn();
        whenStartingLoginScreen();
        thenRefreshTokenIsCalled();
    }

---------------------------------------------------------------------------------------
    @Test
    public void startLogin_RefreshToken_Successful_WhenLoggedIn_ShowsApp() {
        givenUserIsLoggedIn();
        whenStartingLoginScreen();
        thenRefreshTokenIsCalledAndSucceeds();
        thenAppIsShown();
    }

    @Test
    public void startLogin_RefreshToken_Failed_WhenLoggedIn_ShowsLoginScreen() {
        givenUserIsLoggedIn();
        whenStartingLoginScreen();
        thenRefreshTokenIsCalledButFails();
        thenLoginScreenIsCalled();
    }

I am not sure how to mock the thenRefreshTokenIsCalledButFails() and thenRefreshTokenIsCalledAndSucceeds()

For thenRefreshTokenIsCalled what I do is I have an instance of the class the method is in, same class the startLogin is in, lets call it AuthViewer

so I do authViewer.refreshToken(); or authViewer.startLogin();

For LogInScreenIsShown and thenAppIsShown I do:

private void thenLogInScreenIsShown() {
        Mockito.verify(mockView, Mockito.only()).showLoginScreen(Mockito.any());
    }

    private void thenAppIsShown() {
        Mockito.verify(mockView, Mockito.only()).showApp();
    }

mockView is the instance of the class View I am using which contains showApp and showLoginScreen:

mockView = Mockito.mock(View.class);

I tried something like:

private void givenTokenCanBeRefreshed() {
        mockAuthController.errorReturnedByRefresh = null;
    }

But I keep getting wanted but not invoked errors.

Any guidance would be helpful.

Aucun commentaire:

Enregistrer un commentaire