BAEL-3853: Helpful NPE in Java 14

This commit is contained in:
Eduard Ardeleanu 2020-03-20 17:28:47 +02:00
parent b5fb4b4182
commit d3b35f9f0c
2 changed files with 93 additions and 0 deletions

View File

@ -0,0 +1,56 @@
package com.baeldung.java14.helpfulnullpointerexceptions;
public class HelpfulNullPointerException {
public static void main(String[] args) {
Employee employee = null;
employee.getName();
}
public String getEmployeeEmailAddress(Employee employee) {
String emailAddress = employee.getPersonalDetails().getEmailAddress().toLowerCase();
return emailAddress;
}
static class Employee {
String name;
PersonalDetails personalDetails;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public PersonalDetails getPersonalDetails() {
return personalDetails;
}
public void setPersonalDetails(PersonalDetails personalDetails) {
this.personalDetails = personalDetails;
}
}
static class PersonalDetails {
String emailAddress;
String phone;
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.java14.helpfulnullpointerexceptions;
import org.junit.Test;
import static com.baeldung.java14.helpfulnullpointerexceptions.HelpfulNullPointerException.Employee;
import static com.baeldung.java14.helpfulnullpointerexceptions.HelpfulNullPointerException.PersonalDetails;
import static org.assertj.core.api.Assertions.assertThat;
public class HelpfulNullPointerExceptionUnitTest {
@Test (expected = NullPointerException.class)
public void givenAnEmptyPersonalDetails_whenEmailAddressIsAccessed_thenThrowNPE() {
var helpfulNPE = new HelpfulNullPointerException();
var employee = new Employee();
employee.setName("Eduard");
employee.setPersonalDetails(new PersonalDetails());
helpfulNPE.getEmployeeEmailAddress(employee);
}
@Test
public void givenCompletePersonalDetails_whenEmailAddressIsAccessed_thenSuccess() {
var helpfulNPE = new HelpfulNullPointerException();
var emailAddress = "eduard@gmx.com";
var employee = new Employee();
employee.setName("Eduard");
var personalDetails = new PersonalDetails();
personalDetails.setEmailAddress(emailAddress.toUpperCase());
personalDetails.setPhone("1234");
employee.setPersonalDetails(personalDetails);
assertThat(helpfulNPE.getEmployeeEmailAddress(employee)).isEqualTo(emailAddress);
}
}