mockito / mockito-kotlin

Using Mockito with Kotlin
MIT License
3.11k stars 202 forks source link

Methods on mock are invoked with matcher argument after verify #345

Closed krichter722 closed 5 years ago

krichter722 commented 5 years ago

In a test

class TheClassTest {

    @Test
    fun testSomeMethodArgumentMatcher() {
        val someService: SomeService = mock()
        val instance: TheClass = TheClass(someService)
        instance.someMethod("not blank")

        verify(someService).someMethod(anyString())
    }
}

testing

import org.springframework.beans.factory.annotation.Autowired

class TheClass constructor(@Autowired val someService: SomeService){

    fun someMethod(arg: String) {
        someService.someMethod(arg)
    }
}

and

import org.springframework.stereotype.Service

@Service
open class SomeService {

    fun someMethod(arg: String) {
        println("arg: $arg")
        if(arg.isBlank()) {
            throw IllegalArgumentException("arg mustn't be blank")
        }
    }
}

the verification fails because someMethod is invoked with an empty string, probably taken instead of anyString in verify(someService).someMethod(anyString()).

The verification should succeed because the method has been invoked with a non-blank string. It does so when using Mockito 2.27.0 in a pure Java project.

An SSCCE can be found at https://gitlab.com/krichter/mockito-kotlin-verify-mock-method-invoked/ (CI output at https://gitlab.com/krichter/mockito-kotlin-verify-mock-method-invoked/-/jobs/214957830).

experienced with 2.1.0

nhaarman commented 5 years ago

This is because the someMethod is non-open - thus final - making it impossible for Mockito to stub the implementation. The pure Java project probably doesn't have the final modifier for someMethod, making it succeed there.

Either make it open, use the 'all-open' plugin, or Mockito's mock-maker-inline.