Can Mockito verify parameters based on their values at the time of method call?

后端 未结 4 754

I have a Foo class which is SUT and a Bar class, which is its collaborator. Foo calls run(List values) on t
4条回答
  •  渐次进展
    2020-12-03 17:58

    The answer of Dawood ibn Kareem worked for me but I lacked an example, also I use Kotlin and Mockito-Kotlin, so my solution is like this:

    class Foo(var mutable: String)
    
    interface Bar {
        fun run(foo: Foo)
    }
    
    @Test fun `validate mutable parameter at invocation`() {
        val bar = mock()
    
        var valueAtInvocation: String? = null
        whenever(bar.run(any())).then {
            val foo = it.arguments.first() as Foo
            valueAtInvocation = foo.mutable // Store mutable value as it was at the invocation
            Unit // The answer
        }
    
        val foo = Foo(mutable = "first")
        bar.run(foo)
        valueAtInvocation isEqualTo "first"
    
        foo.mutable = "second"
        bar.run(foo)
        valueAtInvocation isEqualTo "second"
    }
    

    valueAtInvocation will represent the value of the mutable property foo.mutable at the last invocation of bar.run(foo). Should also be possible to do assertions within the then {} block.

提交回复
热议问题