Skip to content

any<SpecificType>() matcher ignores the concrete type and matches all types #1296

@Zordid

Description

@Zordid

Expected Behavior

When verifying calls, using any<SpecificType>() as an argument, it should only fit if the call happened with this SpecificType - for other types it should fail!
inline fun <reified T : Any> any(): T even has a more obvious sibling fun <T : Any> any(classifier: KClass<T>): T... problem/bug is the same here, the given classifier is completely ignored.

Interestingly, replacing any<SpecificType>() with capture(slot<SpecificType>()) does this correctly - even though the capture slot is not really wanted or needed.

Current Behavior

When you verify a call on a function fun call(arg: Any) using verify { call(any<String>()) }, it verifies OK for any argument type called, not only String type!

Context

Please provide any relevant information about your setup. This is important in case the issue is not reproducible except for under certain conditions.

  • MockK version: 1.13.12
  • OS: MacOS Sonoma
  • Kotlin version: 1.9.25
  • JDK version: 11
  • JUnit version: 5.9.1
  • Type of test: unit test

Minimal reproducible code (the gist of this issue)

interface System {
    fun send(message: Any)
}

fun myCodeUnderTest(system: System) {
    system.send("foo")
}

class MockkDemo {

    @Test
    fun `this test should fail, but does not`() {
        val mockProducer = mockk<System>(relaxed = true)

        myCodeUnderTest(mockProducer)

        // I expect the following line to fail, because the message type for arg was a String, not an Int!
        verifySequence { mockProducer.send(any<Int>()) }
        // same here, even more obvious to me that the second argument should only match Int type
        verifySequence { mockProducer.send(any(Int::class)) }
    }

    @Test
    fun `using capture instead of any works correctly`() {
        val mockProducer = mockk<System>(relaxed = true)

        myCodeUnderTest(mockProducer)

        // this works just fine - it fails as it should!
        verifySequence { mockProducer.send(capture(slot<Int>())) }
    }

}

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions