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)
NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.
Java 8 introduced an Optional class which is a nicer way to avoid NullPointerExceptions. You can use Optional to encapsulate the potential null values and pass or return it safely without worrying about the exception. Without Optional, when a method signature has return type of certain object.
Programmers typically catch NullPointerException under three circumstances: The program contains a null pointer dereference. Catching the resulting exception was easier than fixing the underlying problem. The program explicitly throws a NullPointerException to signal an error condition.
NullPointerException is thrown when an application attempts to use an object reference that has the null value. These include: Calling an instance method on the object referred by a null reference. Accessing or modifying an instance field of the object referred by a null reference.
Answer: Some of the best practices to avoid NullPointerException are: Use equals() and equalsIgnoreCase() method with String literal instead of using it on the unknown object that can be null. Use valueOf() instead of toString() ; and both return the same result. Use Java annotation @NotNull and @Nullable.
Use PatternsCompat instead of Patterns
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";
}
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