Hi I’m using kotlinx.datetime and mockk. I would like to mock `TimeZone.currentSystemDefault()` at a...
i
Hi I’m using kotlinx.datetime and mockk. I would like to mock 
TimeZone.currentSystemDefault()
 at a below code, but error occurs, 
java.lang.NoClassDefFoundError: kotlinx/serialization/KSerializer
When 
mockkObject(TimeZone)
 was called, the error happened. Why happens error? Enviroments • kotlinx.datetime 0.2.1 • kotlin-stdlib-jdk7 1.5.21 • mockk 1.12.0
Copy code
class MyTest {
    @Before
    fun setup() {
        mockkObject(TimeZone)
    }

    @After
    fun tearDown() {
        unmockkAll()
    }

    @Test
    fun test() {
        every {
            TimeZone.currentSystemDefault()
        } returns TimeZone.of("Asia/Tokyo")

        assertEquals(TimeZone.currentSystemDefault(), TimeZone.of("Asia/Tokyo"))
    }
}
Copy code
Aug 20, 2021 7:43:20 PM io.mockk.impl.log.JULLogger warn
WARNING: Failed to transform class kotlinx/datetime/TimeZone$Companion
java.lang.NoClassDefFoundError: kotlinx/serialization/KSerializer
	at java.lang.Class.getDeclaredMethods0(Native Method)
	at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
	at java.lang.Class.getDeclaredMethods(Class.java:1975)
...
w
Simply, just add
org.jetbrains.kotlinx:kotlinx-serialization-core:1.2.2
to your dependencies
https://github.com/Kotlin/kotlinx-datetime/blob/master/core/build.gradle.kts#L156 kotlinx.datetime uses kotlinx.serialization but it declared as
compileOnly
. This means that
TimeZone
is serializable when our project has kotlinx.serialization as a dependency, but the jar of kotlinx.datetime includes no runtime of kotlinx.serialization. In most cases, this works well; since we can not serialize any objects without kotlinx.serialization in our dependencies (compilation error). But unfortunately, mockk uses reflection. So it can reach
KSerializer
, which is normally unreachable. And your project doesn't have the runtime of kotlinx.serialization at this time, so JVM cannot load the class and finally a
NoClassDefFoundError
is thrown. This is the reason why it happens.
👀 1
i
@wcaokaze I added 
testRuntimeOnly org.jetbrains.kotlinx:kotlinx-serialization-core:1.2.2
  in 
build.gradle
 , so the test was successful! Thanks for help😘
👌🏻 1