NullPointerException on validating email

Tags: , , , ,

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.

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

The error I am getting is,

at com.tryout.hemanth.expensetracker.service.LoginService.validate(


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";

Source: stackoverflow