NPE在调用mock时

时间:2017-03-31 16:48:33

标签: java android unit-testing mockito

我刚刚开始测试,我也在我的Android应用中使用MVP模式。

目前我有一位演示者,它使用以下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();
    }
}

}

所以现在我的测试代码是:

public class SignUpPresenterTest {

@Mock
private SignUpMVP.View view;

@Mock
private EmailValidator validator;

private SignUpPresenter presenter;

private String email = "name@gmail.com";
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

2 个答案:

答案 0 :(得分:2)

之所以发生这种情况,是因为你在嘲笑EmailValidator,但你没有在SignUpPresenter内使用该对象。

您应该在构造函数中传递引用:

presenter = new SignUpPresenter(view, validator);

或方法签名:

presenter.onButtonSignUpClicked(email, password, username, validator);

那么你的主持人应该是这样的:

public class SignUpPresenter {

    private View view;
    private EmailValidator validator;

    public SignUpPresenter(View view, EmailValidator validator) {
        this.view = view;
        this.validator = validator;
    }

    private void onButtonSignUpClicked(String email, String password, String username) {
        //Your code...
        boolean isValid = validator.isValidEmail(email);
    }
}

答案 1 :(得分:2)

你应该试试这个,因为你需要提供一个真实的界面实现

@InjectMocks
private EmailValidator validator = new EmailValidatorImpl();