Search code examples
kotlinjmockit

How to mock a top-level-function in kotlin with jmockit


Assuming the I have a function to be test below, declare at the file named "Utils.kt"

//Utils.kt
fun doSomething() = 1

Then we create a test class to test it

//UtilsTest.kt
@RunWith(JMockit::class)
class UtilsTest {
    @Test
    fun testDoSomething() {
        object : Expectation() {
            init {
                doSomething()
                result = 2
            }
        }

        assertEquals(2, doSomething())
    }
}

I want to mock doSomething, make it return 2, but it won't work, actual result is 1

Is there any workaround for this purpose?


Solution

  • A workaround mock it in Java side as you cannot reference the UtilsKt class from Kotlin files.

    @RunWith(JMockit.class)
    public final class UtilsFromJavaTest {
        @Test
        public final void testDoSomething(@Mocked @NotNull final UtilsKt mock) {
            new Expectations() {
                {
                    UtilsKt.doSomething();
                    this.result = 2;
                }
            };
            Assert.assertEquals(2, UtilsKt.doSomething());
        }
    
    }