Hello i try to use mockito, to verify user password if invalid i want to verify it show error message.
But i got this following error :
Wanted but not invoked:
loginView.showPasswordError();
-> at android.fanjavaid.com.tdd_android_login.LoginActivityTest.invalidPassword_notLoggedIn_showPasswordError(LoginActivityTest.java:84)
However, there was exactly 1 interaction with this mock:
loginView.showEmailError();
-> at android.fanjavaid.com.tdd_android_login.presenter.LoginPresenterImpl.validateInput(LoginPresenterImpl.java:23)
Here is my test method :
@Test
public void invalidEmail_notLoggedIn_showEmailError() {
LoginPresenter presenter = new LoginPresenterImpl(loginView, validator);
presenter.validateInput(user);
verify(loginView).showEmailError();
}
@Test
public void invalidPassword_notLoggedIn_showPasswordError() {
when(user.getEmailAddress()).thenReturn("fanjavaid@gmail.com");
LoginPresenter presenter = new LoginPresenterImpl(loginView, validator);
presenter.validateInput(user);
verify(loginView).showPasswordError();
}
I already mock the email user in invalidPassword_notLoggedIn_showPasswordError()
with valid input, but i still get that error message.
Here is my Presenter implementation :
@Override
public void validateInput(User user) {
if (!validator.validateEmail(user.getEmailAddress())) {
view.showEmailError();
} else if (validator.validatePassword(user.getPassword())) {
view.showPasswordError();
}
}
What i am missing for?
Thank you
ā ANSWER
After several minutes explore again, i found something interesting. I forgot to add mock to one class. Below i mock some classes moreless like this :
@RunWith(MockitoJUnitRunner.class)
public class LoginActivityTest {
@Mock User user;
@Mock LoginView loginView;
@Mock MyValidator validator;
LoginPresenter presenter;
@Before
public void beforeTest() {
presenter = new LoginPresenterImpl(loginView, validator);
}
...
You can see that i mock validator class.
I got the error because in invalidPassword_notLoggedIn_showPasswordError()
method i didn't add mock value for email validation.
// Mock validation
when(validator.validateEmail(user.getEmailAddress())).thenReturn(true);
If i don't mock it, it will ask about showEmailError()
but we just verify showPasswordError()
This cause my implementation using condition to check one by one, started from check email is valid or not, then password valid or not. If email doesn't exists and return value from validator doesn't exists the error will occured.
So i need to mock email address as valid and mock validator to return true(valid email).
That's my explanation and hope can help anyone who try mockito.