From 545e2024b13c72b92ae7cd715f64de2619d7de69 Mon Sep 17 00:00:00 2001 From: whiskels Date: Fri, 12 Jul 2024 10:34:23 +0300 Subject: [PATCH] T-38: fixed NPE in comparator --- .../reporting/domain/HasBirthday.java | 2 +- .../reporting/domain/HasBirthdayTest.java | 62 +++++++++++++++++++ 2 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 src/test/java/com/whiskels/notifier/reporting/domain/HasBirthdayTest.java diff --git a/src/main/java/com/whiskels/notifier/reporting/domain/HasBirthday.java b/src/main/java/com/whiskels/notifier/reporting/domain/HasBirthday.java index 0c747bfe..c7b0c895 100644 --- a/src/main/java/com/whiskels/notifier/reporting/domain/HasBirthday.java +++ b/src/main/java/com/whiskels/notifier/reporting/domain/HasBirthday.java @@ -5,7 +5,7 @@ public interface HasBirthday { static Comparator comparator() { - return Comparator.comparing(T::birthday).thenComparing(T::name); + return Comparator.comparing(T::birthday, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(T::name, Comparator.nullsLast(Comparator.naturalOrder())); } diff --git a/src/test/java/com/whiskels/notifier/reporting/domain/HasBirthdayTest.java b/src/test/java/com/whiskels/notifier/reporting/domain/HasBirthdayTest.java new file mode 100644 index 00000000..771c20a7 --- /dev/null +++ b/src/test/java/com/whiskels/notifier/reporting/domain/HasBirthdayTest.java @@ -0,0 +1,62 @@ +package com.whiskels.notifier.reporting.domain; + +import lombok.Builder; +import org.junit.jupiter.api.Test; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +class HasBirthdayTest { + + @Test + void testComparator() { + var first = "FIRST"; + var second = "SECOND"; + var third = "THIRD"; + var fourth = "FOURTH"; + + List input = new ArrayList<>(); + input.add( + HasBirthdayImpl.builder() + .name(fourth) + .birthday(null) + .build() + ); + input.add( + HasBirthdayImpl.builder() + .name(null) + .birthday(null) + .build() + ); + input.add( + HasBirthdayImpl.builder() + .name(first) + .birthday(LocalDate.now()) + .build() + ); + input.add( + HasBirthdayImpl.builder() + .name(second) + .birthday(LocalDate.now().plusDays(1)) + .build() + ); + input.add( + HasBirthdayImpl.builder() + .name(third) + .birthday(LocalDate.now().plusDays(1)) + .build() + ); + + input.sort(HasBirthday.comparator()); + + assertThat(input).extracting(HasBirthday::name) + .containsExactly(first, second, third, fourth, null); + } + + @Builder + record HasBirthdayImpl(String name, LocalDate birthday) implements HasBirthday { + } +} \ No newline at end of file