Skip to content

Commit

Permalink
Merge pull request #518 from gmazzo/feature/mockstatic-hard-reference…
Browse files Browse the repository at this point in the history
…-support

Added `mockkStatic` hard reference support
  • Loading branch information
Raibaz committed Nov 23, 2020
2 parents 028afca + 8befb6f commit 1466af1
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 0 deletions.
6 changes: 6 additions & 0 deletions README.md
Expand Up @@ -792,6 +792,12 @@ verify {
}
```

On `jvm` environments you can replace the class name with a function reference:
```kotlin
mockkStatic(Obj::extensionFunc)
```
Note that this will mock the whole `pkg.FileKt` class, and not just `extensionFunc`.

If `@JvmName` is used, specify it as a class name.

KHttp.kt:
Expand Down
28 changes: 28 additions & 0 deletions mockk/jvm/src/main/kotlin/io/mockk/MockK.kt
@@ -1,10 +1,38 @@
@file:JvmName("JVMMockKKt")
package io.mockk

import io.mockk.impl.JvmMockKGateway
import kotlin.reflect.KFunction
import kotlin.reflect.jvm.javaMethod

actual object MockK {
actual inline fun <T> useImpl(block: () -> T): T {
MockKGateway.implementation = JvmMockKGateway.defaultImplementationBuilder
return block()
}
}

/**
* Returns the defining top-level extension function's [Class].
*/
inline val KFunction<*>.declaringKotlinFile
get() = checkNotNull(javaMethod) { "$this is not a top-level extension function" }
.declaringClass.kotlin

/**
* Builds a static mock. Any mocks of this function's declaring class are cancelled before it's mocked
*/
inline fun mockkStatic(vararg functions: KFunction<*>) =
mockkStatic(*functions.map { it.declaringKotlinFile }.toTypedArray())

/**
* Cancel static mocks.
*/
inline fun unmockkStatic(vararg functions: KFunction<*>) =
unmockkStatic(*functions.map { it.declaringKotlinFile }.toTypedArray())

/**
* Builds a static mock and unmocks it after the block has been executed.
*/
inline fun mockkStatic(vararg functions: KFunction<*>, block: () -> Unit) =
mockkStatic(classes = *functions.map { it.declaringKotlinFile }.toTypedArray(), block = block)
45 changes: 45 additions & 0 deletions mockk/jvm/src/test/kotlin/io/mockk/it/StaticMockJVMTest.kt
@@ -0,0 +1,45 @@
package io.mockk.it

import io.mockk.every
import io.mockk.mockkStatic
import io.mockk.verify
import kotlin.test.Test
import kotlin.test.assertEquals

class StaticMockJVMTest {

@Test
fun simpleStaticMock() {
mockkStatic(Int::op)

every { 5 op 6 } returns 2

assertEquals(2, 5 op 6)

verify { 5 op 6 }
}

@Test
fun clearStateStaticMock() {
mockkStatic(Int::op)

every { 5 op 6 } returns 2

assertEquals(2, 5 op 6)

verify { 5 op 6 }

mockkStatic(Int::op)

verify(exactly = 0) { 5 op 6 }

assertEquals(11, 5 op 6)

every { 5 op 6 } returns 3

assertEquals(3, 5 op 6)

verify { 5 op 6 }
}

}

0 comments on commit 1466af1

Please sign in to comment.