我剛剛開始測試,我也在我的android應用中使用MVP
模式。NPE當調用模擬
目前我有一個使用下面的Android代碼來測試,如果電子郵件地址是有效的一個主持人:
android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches()
因爲它不可能與本地JVM
單元測試,我決定到後面躲起來,對其進行測試接口:
public interface EmailValidator {
boolean isValidEmail(CharSequence target);
}
和這裏的實現:
public class EmailValidatorImpl implements EmailValidator {
@Override
public boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
}
所以現在我的測試代碼:
公共類SignUpPresenterTest {
@Mock
private SignUpMVP.View view;
@Mock
private EmailValidator validator;
private SignUpPresenter presenter;
private String email = "[email protected]";
private String password = "ABCDabcd";
private String username = "username";
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
presenter = new SignUpPresenter(view);
}
@Test
public void onButtonSignUpClicked() throws Exception {
when(validator.isValidEmail(email))
.thenReturn(true);
presenter.onButtonSignUpClicked(email, password, username);
verify(view).executeSignUpService();
}
}
,現在我得到一個NPE當上面的調用代碼:EmailValidatorImpl.isValidEmail()
java.lang.NullPointerException
at com.example.signup.helpers.EmailValidatorImpl.isValidEmail(EmailValidatorImpl.java:20)
at com.example.signup.SignUpPresenter.showErrors(SignUpPresenter.java:67)
at com.example.signup.SignUpPresenter.onButtonSignUpClicked(SignUpPresenter.java:25)
at com.example.signup.SignUpPresenterTest.onButtonSignUpClicked(SignUpPresenterTest.java:43)
和我的問題是:這不是我應該如何使用Mockito
?有什麼我可以做的測試我的代碼,並避免NPE
?