Search code examples
kotlinmockitoargument-matching

ArgumentMatcher for Kotlin


I'm trying to use ArgumentMatcher in my tests. I do next:

Mockito.`when`(someRepository.save(
        argThat { it.name == someName } // Here I want to do mock for all objects with name someName
    )).thenReturn(save(someEntity))

And I get next error: Type inference failed: Not enough information to infer parameter T in fun when(p0: T!): OngoingStubbing!

How properly write ArgumentMatcher in Kotlin?


Solution

  • I found a solution by adding ArgumentMatcher from java class. My IDE converted it to Kotlin:

    In java:

    Mockito.when(someRepository.save(ArgumentMatchers.argThat(entity-> entity.getName().equals("someName")
                && entity.getDescription().equals("somedescritpion")
                ))));
    

    In Kotlin:

    Mockito.`when`<Any>(someRepository.save(ArgumentMatchers.argThat { (name, _, description, ) ->
            (name == "someName" && description == "somedescritpion"
                    )
        }))
    

    Note: You should add _ if you have some fields which you don't want to consider in the matcher.