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??") <== ???
- Tried using
coevery
as well. - Happens in
setup
ortest
methods. - I import
io.mockk:mockk
. - I only use
mockk
no junit or other testing frameworks. - In my production test, this behavior causes my tests to fail as the static method relies on system setup not available in tests.
- Gradle JVM = 17.0.9 - I don't get access exceptions as MockK mentions here.
- Tried following this accepted Github answer mentioning to use mockObject for companion objects.
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 andprint
insidetestStaticMethod
doesn't happen. I'm using JUnit5 here instead of JUnit4, but I don't think it matters.