How do you test an extension function that is a cl...
# test
g
How do you test an extension function that is a class member. Lets consider this example
Copy code
class DateUtils {
  fun LocalDateTime.setTimeZone(targetTimeZone: String): LocalDateTime {
        return ZonedDateTime.of(
            this,
            ZoneId.of(targetTimeZone)
        ).toLocalDateTime()
    }
}

@Test
fun `It should set time zone`() {
  val msgDateStr = "2020-03-07T11:55:00"
  val format = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss")
  al currDate = LocalDateTime.parse(msgDateStr, format)
  assertEquals("2020-03-07T11:55-05:00[America/New_York]", DateUtils.setTimeZone(currDate, "America/NewYork"))
}

DateUtils.setTimeZome(...) // I get a Unresolved reference: setTimeZone
d
Is there any reason why the extension function is a member? This is pretty unusual
g
probably bad design from my part. what would be the right way to create a class and extensions functions from that class
a
Copy code
with(DateUtils()){
            assertEquals("2020-03-07T11:55-05:00[America/New_York]", currDate.setTimeZone( "America/NewYork"))
        }
it compiles, but assert fails
g
from
currDate.setTimeZone(...) // Unresolved reference: setTimeZone
IDEA complains
strange that
DateTimeFormatter.ofPattern(…) // Unresolved reference: ofPattern
a
perhaps imports are different..
message has been deleted
g
🤔
d
Top level, without any wrapping class.
Copy code
fun LocalDateTime.setTimeZone(targetTimeZone: String): LocalDateTime {
        return ZonedDateTime.of(
            this,
            ZoneId.of(targetTimeZone)
        ).toLocalDateTime()
    }
In
LocalDateTimeExt.kt
file for example
g
I see
d
Next is be sure that you have all dependencies in the test source set also. I come from the gradle world and there it is
testImplementation
ect. No idea how it is handled in maven though
g
that worked. takin the extension outside the class