Search code examples
javaandroidandroid-studiojunitjunit4

NullPointerException on validating email


I am writing a unit test to check the email validation logic. The logic is throwing null pointer exception when you run the test. But it works fine with emulator. Can someone help me solving this?

public static String validate(String email, String password) {
        if (email == null || email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            return "Enter valid email address";
        }
        if (password.isEmpty() || password.length() < 4) {
            return "Password should be between 4 and 10 alphanumeric characters";
        }
        return null;
}

Below is my unit test.

@Test
public void validateShouldReturnMessageIfYouPassAnInvalidEmail() throws Exception {
    String validateMessage = LoginService.validate("abcdef", "password");
    assertEquals("Enter valid email address", validateMessage);
}

The error I am getting is,

java.lang.NullPointerException
at com.tryout.hemanth.expensetracker.service.LoginService.validate(LoginService.java:11)

Solution

  • android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches() exists since API level 8, May be your emulator is prior than this.

    So I suggest Adding custom EMAIL_ADDRESS_PATTERN string as suggested in this answer and check it like

    if (email == null || email.isEmpty() || !EMAIL_ADDRESS_PATTERN.matcher(email).matches()){
         return "Enter valid email address";
    }