Create an Android kotlin project.

Add dependencies to app/build.gradle

testImplementation 'org.mockito:mockito-core:2.+'
testImplementation 'org.jetbrains.spek:spek-api:1.1.2'
testImplementation 'org.jetbrains.spek:spek-junit-platform-engine:1.1.2'
testImplementation 'org.junit.platform:junit-platform-runner:1.0.0-M4'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.0.0-M4'

Implement an interface DataSource.

interface DataSource {
    fun fetch(inputA: Int, inputB: Arg): Int

Implement a class Arg.

class Arg(name: String) {
    val name = name.toUpperCase()

Replace content of test file ExampleUnitTest.kt to

class MomentsPresenterSpec : Spek({

    val dataSource = Mockito.mock(

    beforeEachTest {

    afterEachTest {

    describe("DataSource fetch") {

        given("with any input data") {
            beforeEachTest {
                Mockito.`when`(dataSource.fetch(anyInt(), any(

            it("should return 1") {
                assertEquals(1, dataSource.fetch(0, Arg("Jie")))

Run test, then you would got: java.lang.IllegalStateException: any( must not be null

That’s because any() always return default value of given class, for primitive type, it’ll return primitive default value, for class, null will return.

Kotlin method does not accept null value if not declared nullable as arg: ClassName?.

You can override any() function to solve this problem.

Add a utils file Extensions.kt to test project.

fun <T> any(): T {
    return uninitialized()

fun <T> uninitialized(): T = null as T

Make some change to ExampleUnitTest.kt


Mockito.`when`(dataSource.fetch(anyInt(), any(


Mockito.`when`(dataSource.fetch(anyInt(), any())).thenReturn(1)

Add import import com.jmengxy.kotlinspek.utils.any

Re-Run test, everything works fine.

Github Repo


Using spek in kotlin

Befriending Kotlin and Mockito