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