mockito-kotlin
mockito-kotlin copied to clipboard
how to verify a static method in kotlin
Having a kotlin singleton with static methods
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/verify static method using mockito in kotlin?
@lannyf77 : Were you able to figure out a solution for this?
@aakash1313 @lannyf77 Basically look at the decompiled kotlin classes. You will see there are more than 1 layer of static functions / classes. Which are really difficult to clear from tests. So either use interface level of abstraction for mocking. Or use static / singleton java classes for only 1 layer of static / final classes.
@lannyf77 In Kotlin lambdas are written like this:
theMock.verify({ TestSingleton.staticMethod(any(Context::class.java), "test") }, times(1))
// or
theMock.verify(times(1)) { TestSingleton.staticMethod(any(Context::class.java)) }
not the way Java does.
In your code you have mix of Java syntax, that's why it's a syntax error.