Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android.util.Patterns.EMAIL returns null during unit test

Tags:

android

junit

I have a code which has android.util.Patterns.EMAIL_ADDRESS in a validator. It runs fine when it's run against a device but when I run this code in unit test, it returns null. Also, I tried copy and pasting the internal code in the patterns as the following example.

validateEmail1 works // whyyy???

validateEmail2 returns null

private static final Pattern EMAIL = Pattern.compile(
        "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
                "\\@" +
                "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
                "(" +
                "\\." +
                "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
                ")+"
);

public boolean validateEmail1(String email) {
    return EMAIL.matcher(email).matches();
}

public boolean validateEmail2(String email) {
    return Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
like image 465
Rubin Yoo Avatar asked May 13 '16 15:05

Rubin Yoo


1 Answers

Okay I found that the problem comes from the classes in android.jar. These classes are mocked during unit test (see tools.android.com/tech-docs/unit-testing-support) and I have to use robolectric to test the class.

like image 186
Rubin Yoo Avatar answered Sep 17 '22 05:09

Rubin Yoo