2017-03-31 74 views
0

我剛剛開始測試,我也在我的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

回答

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); 
    } 
} 
2

你應該試試這個,因爲你需要提供一個真正實現你的接口的

@InjectMocks 
private EmailValidator validator = new EmailValidatorImpl(); 
相關問題