Skip to content

Commit aaec0fc

Browse files
committed
KTLN-547: Unit tests for Sorting String dates
Signed-off-by: Diego Torres <[email protected]>
1 parent e9aae86 commit aaec0fc

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package com.baeldung.listofdates
2+
3+
import org.junit.jupiter.api.Assertions.assertEquals
4+
import org.junit.jupiter.api.Test
5+
import java.time.LocalDate
6+
import java.time.format.DateTimeFormatter
7+
import kotlin.test.assertNotNull
8+
9+
class SortingListOfStringDatesTest {
10+
11+
@Test
12+
fun `given a list of string dates when sorting with sortedDescending then a sorted list is generated`() {
13+
val dates = listOf("31-12-2023", "01-01-2023", "15-06-2023")
14+
15+
val formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy")
16+
val sortedDates = dates.map { LocalDate.parse(it, formatter) }
17+
.sortedDescending()
18+
.map { it.format(formatter) }
19+
20+
val expectedSortedDates = listOf("31-12-2023", "15-06-2023", "01-01-2023")
21+
22+
assertNotNull(sortedDates)
23+
assertEquals(sortedDates, expectedSortedDates)
24+
}
25+
26+
@Test
27+
fun `given a list of string dates when sorting with sortedByDescending then a sorted list is generated`() {
28+
val dates = listOf("31-12-2023", "01-01-2023", "15-06-2023")
29+
30+
val dateTimeFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy")
31+
32+
val sortedDates = dates.sortedByDescending {
33+
LocalDate.parse(it, dateTimeFormatter)
34+
}
35+
36+
val expectedSortedDates = listOf("31-12-2023", "15-06-2023", "01-01-2023")
37+
38+
assertNotNull(sortedDates)
39+
assertEquals(sortedDates, expectedSortedDates)
40+
}
41+
42+
@Test
43+
fun `given a list of string dates when sorting using custom comparator then a sorted list is generated`() {
44+
val dates = listOf("31-12-2023", "01-01-2023", "15-06-2023")
45+
46+
val sortedDates = dates.sortedWith(compareByDescending {
47+
val (day, month, year) = it.split("-")
48+
"$year-$month-$day"
49+
})
50+
51+
val expectedSortedDates = listOf("31-12-2023", "15-06-2023", "01-01-2023")
52+
53+
assertNotNull(sortedDates)
54+
assertEquals(sortedDates, expectedSortedDates)
55+
}
56+
}

0 commit comments

Comments
 (0)