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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With