Issue
Having a kotlin singleton static method
internal object TestSingleton {
@JvmStatic
fun staticMethod1 (str: String) {
println("+++ === +++ TestSingleton.staticMethod(), $str")
staticMethod2 (str)
}
@JvmStatic
fun staticMethod2 (str: String) {
println("+++ === +++ TestSingleton.staticMethod2(), $str")
}
}
In java test code:
@Test
public void test_staticMethod() {
try (MockedStatic<TestSingleton> theMock = Mockito.mockStatic(TestSingleton.class, CALLS_REAL_METHODS)) {
TestSingleton.staticMethod1("test");
theMock.verify(() -> TestSingleton.staticMethod2(eq("test")), times(1));
}
}
it runs fine but convert to kotlin it does not compile:
@Test
open fun test_staticMethod() {
Mockito.mockStatic(TestSingleton::class.java, Mockito.CALLS_REAL_METHODS).use { theMock ->
staticMethod1("test")
theMock.verify(() -> TestSingleton.staticMethod(any(Context.class), "test"), times(1))
// or
theMock.verify(times(1), () -> TestSingleton.staticMethod(any(Context.class)) )
}
}
having mockito version testImplementation "org.mockito:mockito-inline:3.12.4"
.
How to test static method using mockito in kotlin? Not tried mockk yet since having a lot tests have been working with mockito. Not sure how simple with mockk in this case.
Solution
Here's how to do it in mockk (I highly recommend switching away from Mockito, mockk is just so much easier):
import TestSingleton.staticMethod1
import io.mockk.every
import io.mockk.just
import io.mockk.mockkStatic
import io.mockk.runs
import io.mockk.verify
import org.junit.jupiter.api.Test
internal object TestSingleton {
@JvmStatic
fun staticMethod1(str: String) {
println("+++ === +++ TestSingleton.staticMethod(), $str")
staticMethod2(str)
}
@JvmStatic
fun staticMethod2(str: String) {
println("+++ === +++ TestSingleton.staticMethod2(), $str")
}
}
class StackSign {
@Test
fun test_staticMethod() {
mockkStatic(TestSingleton::class)
every { TestSingleton.staticMethod2("test") } just runs
staticMethod1("test")
verify(exactly = 1) { TestSingleton.staticMethod2("test") }
}
}
BTW, add this to your build.gradle.kts
testImplementation("io.mockk:mockk:1.12.3")
Answered By - PaulNUK
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.