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

后端 未结 4 755

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:45

    Use an Answer to check the value of the argument when the method is called. You can either throw an AssertionError within the Answer if the value is wrong, or you can store the value, and do your assertion at the end.

    0 讨论(0)
  • 2020-12-03 17:54

    You can't call verify() on an object that is not a mock. Is this what you meant?

    Bar collaborator = mock(Bar.class); 
    Foo sut = spy(new Foo(collaborator));
    verify(collaborator).run(expectedList);
    
    0 讨论(0)
  • 2020-12-03 17:57

    Why don't you try using argument capture to acquire the value of expected list when it was run and then you can compare it.

    ArgumentCaptor<List> listCaptor = ArgumentCaptor.forClass(List.class);
    
    verify(collaborator).run(listCaptor.capture());
    
    assertEquals(expectedList, argument.getValue());
    
    0 讨论(0)
  • 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<Bar>()
    
        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.

    0 讨论(0)
提交回复
热议问题