I've made some assumptions about language version and dependencies and run your code:
- Java 8+ (language level 8)
- JUnit 5 (Jupiter)
Your new Employee(...) constructors weren't working because your @AllArgsConstructor is expecting a Date object not a String.
Assuming you're using Java8+, you should use LocalDate instead of Date.
Code coverage yields the following results.
Employee.java: 50%
Uncovered lines:
@Builder
@NoArgsConstructor
// omitted for brevity
@Getter
private LocalDate lastUpdatedTime;
SortByEmployeeIdByDesc: 100%
To cover the new lines, you should consider changing your test class as follows (for example):
@ExtendWith(MockitoExtension.class)
class SortByEmployeeIdByDescTest {
private static final LocalDate MIN_CREATED = LocalDate.of(2020, 10, 10);
private static final LocalDate MIN_LASTUPDATED = LocalDate.of(2020, 10, 10);
@Test
void sortEmpDescloyeeTest() {
Employee emp1 = new Employee("abc", "test", MIN_CREATED, MIN_LASTUPDATED);
Employee emp2 = new Employee("xyz", "test2", LocalDate.of(2022, 3, 4), LocalDate.of(2022, 3, 4));
List<Employee> sortEmp = new ArrayList<>();
sortEmp.add(emp1);
sortEmp.add(emp2);
sortEmp.sort(new SortByEmployeeIdByDesc());
assertEquals(emp1, sortEmp.get(1));
}
@Test
void noArgsConstructorTest() {
Employee employee = new Employee();
assertNull(employee.getEmpId());
assertNull(employee.getLastUpdatedTime());
}
@Test
void builderTest() {
Employee expectedEmployee = new Employee("testId", "test", MIN_CREATED, MIN_LASTUPDATED);
Employee employee = Employee.builder()
.empId("testId")
.empName("test")
.createdTime(MIN_CREATED)
.lastUpdatedTime(MIN_LASTUPDATED)
.build();
assertEquals(expectedEmployee.getEmpId(), employee.getEmpId());
assertEquals(expectedEmployee.getLastUpdatedTime(), employee.getLastUpdatedTime());
}
}
Because you've only declared @Getter on two of the fields, you can't test the others in the builderTest.
If you want to compare all the fields you could do the following:
Add the @EqualsAndHashCode annotation on Employee -
@Builder
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode // this annotation adds equals and hashCode methods
public class Employee
// omitted for brevity
Change the builderTest code as follows -
@Test
void builderTest() {
Employee expectedEmployee = new Employee("testId", "test", MIN_CREATED, MIN_LASTUPDATED);
Employee employee = Employee.builder()
.empId("testId")
.empName("test")
.createdTime(MIN_CREATED)
.lastUpdatedTime(MIN_LASTUPDATED)
.build();
assertEquals(expectedEmployee, employee); // you now use equals
// instead of testing
// each field
// individually
}
Both approaches (with or without the @EqualsAndHashCode annotation) yield 100% code coverage. Bear in mind that unless you have logic in your getters and setters, covering them is usually considered trivial because you are essentially testing Java assignment, which one may assume to work.