Kotlin MockK Static Methods executed instead of mocked

390 Views Asked by At

I have a simple Kotlin MockK test to mock a static method in setup(). However, instead of mocking, the underlying static method is just called? How do you properly mock static methods in Kotlin?

class Test {
    @Before
    fun setup() {
        mockkStatic(StaticClass::class)
        // mockkStatic(StaticClass::testStaticMethod)
        // mockkObject(StaticClass)

        // This calls the static method instead of mocking???
        every { StaticClass.testStaticMethod() } returns Unit  
    }

...

class StaticClass {
    companion object {
        // JvmStatic
        fun testStaticMethod() {
            print("why is this running still??") <== ???
  1. Tried using coevery as well.
  2. Happens in setup or test methods.
  3. I import io.mockk:mockk.
  4. I only use mockk no junit or other testing frameworks.
  5. In my production test, this behavior causes my tests to fail as the static method relies on system setup not available in tests.
  6. Gradle JVM = 17.0.9 - I don't get access exceptions as MockK mentions here.
  7. Tried following this accepted Github answer mentioning to use mockObject for companion objects.
1

There are 1 best solutions below

0
On

The code in your example wouldn't run for me with Missing mocked calls inside every { ... } block error. However, when setup like described here it runs and print inside testStaticMethod doesn't happen. I'm using JUnit5 here instead of JUnit4, but I don't think it matters.

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class Test {
    @BeforeAll
    fun setup() {
        mockkObject(StaticClass)
        every { testStaticMethod() } just Runs
    }

    @AfterAll
    fun tearDown() {
        unmockkObject(StaticClass)
    }

    @Test
    fun mainTest() {
        testStaticMethod()
    }
}