I have DateUtil.kt file which contains.
fun getFirstDayOfTheWeek(): String {
val firstDay: LocalDate = LocalDate.now(ZoneId.of(DateConstants.IST_ZONE_ID))
.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY))
return firstDay.toString()
}
How can i test this? There is no class and just functions. Using spring boot,
@ExtendWith(SpringExtension.class)
works at a class level.
Should i still create a DateUtilTest class for it , or is there a way to test without creating a class?
@ExtendWith(SpringExtension::class)
class DateUtilsTest {
@Test
fun getFirstDayOfTheWeekTest() {
}
}
Also, Can someone help with how this function can be tested? Should i mock the LocalDate library?
You don't need SpringExtension
to test simple non-spring code. All you need a simple test in a class.
Couple of things to consider while designing such function. LocalDate.now()
makes the function impure. Instead this Date should come as a parameter to the function, so it is easier to test. With Kotlin, you can initialize with default value, so the signature does not change for function callers.
fun getFirstDayOfTheWeek(date: LocalDate = LocalDate.now()): String {
val firstDay: LocalDate = date.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY))
return firstDay.toString()
}
class DateUtilKt {
@Test
fun testFirstDayOfTheWeek() {
val day = getFirstDayOfTheWeek(LocalDate.of(2020, 5,22))
assertEquals("2020-05-18", day)
}
}