mockito-kotlin icon indicating copy to clipboard operation
mockito-kotlin copied to clipboard

how to verify a static method in kotlin

Open lannyf77 opened this issue 3 years ago • 3 comments
trafficstars

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)) )

        }
    }

enter image description here having mockito version testImplementation "org.mockito:mockito-inline:3.12.4".

How to test/verify static method using mockito in kotlin?

lannyf77 avatar Mar 10 '22 21:03 lannyf77

@lannyf77 : Were you able to figure out a solution for this?

aakash1313 avatar May 31 '22 00:05 aakash1313

@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.

navinpd avatar Jun 09 '22 14:06 navinpd

@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.

geaden avatar Jun 28 '23 10:06 geaden