Search code examples
javaandroidmockitojunit4

Test if another method is called from a class using JUnit or Mockito


I have a class like this

public class LoginPresImpl implements LoginAPIInterface.LoginDataListener, LoginAPIInterface.LoginPresenter{
    LoginAPIInterface.LoginView loginView;
    LoginAPIInterface.LoginDataInteractor loginDataInteractor;

    public  LoginPresImpl(LoginAPIInterface.LoginView loginView) {
        this.loginView = loginView;
        loginDataInteractor=new LoginDataModel(this);
    }

    @Override
    public void getLoginUpdateData(String username, String password,String registrationToken) {
        loginDataInteractor.getLoginData(username,password,registrationToken);
    }

}

I want to test if calling

getLoginUpdateData()

will call the getLoginDate() method of loginDataInteractor. I have created a test class like this

public class LoginPresImplTest {
    LoginAPIInterface.LoginDataInteractor loginDataInteractorMock;
    LoginAPIInterface.LoginView loginViewMock;
    LoginPresImpl loginPres;
    @Before
    public void setUp(){
        loginDataInteractorMock = Mockito.mock(LoginAPIInterface.LoginDataInteractor.class);
        loginViewMock = Mockito.mock(LoginAPIInterface.LoginView.class);
        loginPres = Mockito.spy(LoginPresImpl.class);


    }
    @Test
    public void getLoginUpdateData() {
        loginPres.getLoginUpdateData("01","","");
        verify(loginPres).getLoginUpdateData("01","","");

    }

But I don't know how to check if calling

getLoginUpdateData()

will eventually call

loginDataInteractor.getLoginData()

method. How can I test this using JUnit or Mockito.


Solution

  • I want to test if calling

     getLoginUpdateData()
    

    will call the getLoginDate() method of loginDataInteractor.

    loginDataInteractor is a dependency of the code under test (cut) you showed.

    In a UnitTest you only verify the behavior of the cut. You do not verify the behavior of the dependencies. They get their own unit tests.