Skip to content

Commit 11011e6

Browse files
KTLN-547: Unit tests for Sorting String dates (#848)
* KTLN-547: Unit tests for Sorting String dates Signed-off-by: Diego Torres <[email protected]> * KTLN-547: Fixed class name Signed-off-by: Diego Torres <[email protected]> * KTLN-547: Improvements in unit tests Signed-off-by: Diego Torres <[email protected]> --------- Signed-off-by: Diego Torres <[email protected]>
1 parent 15a58ad commit 11011e6

File tree

1 file changed

+53
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)