3

Hi I have the something similar in my production code. A simple method that will throw an exception:

class Production {

    fun doWork(): String {
        throw IllegalArgumentException()
    }
}

However, when I mock this Production class with Mockk, it runs the underlying doWork() method instead of mocking the method call:

import io.mockk.MockKAnnotations
import io.mockk.every
import io.mockk.impl.annotations.MockK
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test

class Test {

    @MockK
    lateinit var production: Production

    @Before
    fun setup() {
        MockKAnnotations.init(this)
    }

    @Test
    fun test() {
        every { production.doWork() } returns "Str"

        assertEquals("Str", production.doWork())
    }
}

The test fails with java.lang.IllegalArgumentException. Shouldn't Mockk be mocking this method call in Production class? I have a feeling that this could be a misunderstanding on my part coming from a Mockito background.

blackpanther
  • 10,998
  • 11
  • 48
  • 78
  • Please post a *complete* minimal example reproducing the problem. – JB Nizet Jul 18 '19 at 18:18
  • Your test passes here. But of course, I had to add and guess a lot of imports, because you didn't post them. So the error is probably in the imports. – JB Nizet Jul 19 '19 at 14:02
  • Interesting @JBNizet I've added the imports - it seems it was the version of Mockk I was using was not good. Version 1.3 had this issue. – blackpanther Jul 19 '19 at 14:09

1 Answers1

0

As of current (Mockk 1.13.4), this is fixed/working as expected:

import io.mockk.MockKAnnotations
import io.mockk.every
import io.mockk.impl.annotations.MockK
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test

class Production {
    fun doWork(): String = throw IllegalArgumentException()
}

class Test {
    @MockK
    lateinit var production: Production

    @BeforeEach
    fun setup() = MockKAnnotations.init(this)

    @Test
    fun test() {
        every { production.doWork() } returns "Str"
        assertEquals("Str", production.doWork())
    }
}
u-ways
  • 6,136
  • 5
  • 31
  • 47