I have a Foo
class which is SUT and a Bar
class, which is its collaborator. Foo
calls run(List
on t
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.
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);
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());
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.