This PR is related to BAEL-5998 (#16384)

* This commit is related to BAEL-5998

This commit aims to add a class named "Employee".

* This commit is related to BAEL-5998

This commit aims to add a test class titled "PrintingNullValuesUnitTest".

* Update PrintingNullValuesUnitTest.java
This commit is contained in:
MohamedHelmyKassab 2024-04-13 22:48:50 +02:00 committed by GitHub
parent 6b4f48eb8f
commit e975895695
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 74 additions and 0 deletions

View File

@ -0,0 +1,44 @@
package com.baeldung.printnullvalues;
import java.util.Objects;
import java.util.Optional;
public class Employee {
private String name;
private int age;
private String department;
public Employee(String name, int age, String department) {
this.name = name;
this.age = age;
this.department = department;
}
public String toStringUsingNullCheck() {
return "Name: " + (name != null ? name : "Unknown") +
", Age: " + age +
", Department: " + (department != null ? department : "Unknown");
}
public String toStringUsingOptional() {
return "Name: " + Optional.ofNullable(name).orElse("Unknown") +
", Age: " + age +
", Department: " + Optional.ofNullable(department).orElse("Unknown");
}
private String getDefaultIfNull(String value, String defaultValue) {
return value != null ? value : defaultValue;
}
public String toStringUsingCustomHelper() {
return "Name: " + getDefaultIfNull(name, "Unknown") +
", Age: " + age +
", Department: " + getDefaultIfNull(department, "Unknown");
}
public String toStringUsingObjects() {
return "Name: " + Objects.toString(name, "Unknown") +
", Age: " + age +
", Department: " + Objects.toString(department, "Unknown");
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.printnullvalues;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class PrintingNullValuesUnitTest {
Employee employee = new Employee(null, 30, null);
String expected = "Name: Unknown, Age: 30, Department: Unknown";
@Test
public void givenNullValues_whenToStringUsingNullCheck_thenCorrectStringReturned() {
assertEquals(expected, employee.toStringUsingNullCheck());
}
@Test
public void givenNullValues_whenToStringUsingOptional_thenCorrectStringReturned() {
assertEquals(expected, employee.toStringUsingOptional());
}
@Test
public void givenNullValues_whenToStringUsingCustomHelper_thenCorrectStringReturned() {
assertEquals(expected, employee.toStringUsingCustomHelper());
}
@Test
public void givenNullValues_whenToStringUsingObjects_thenCorrectStringReturned() {
assertEquals(expected, employee.toStringUsingObjects());
}
}