Is there some alternative to Mockito's Answer in ScalaTest? I was going through its documentation, but didn't find anything.
I would like to, for example, execute some logic on arguments of a stubbed method. In Mockito, I would do something like this:
when(mock.create(any(A.class))).thenAnswer(new Answer() {
Object answer(InvocationOnMock invocation) {
A firstArg = (A) invocation.getArguments()[0];
firstArg.callMethod();
return null;
}
});
In ScalaTest, I'm fine with using Mockito, as well. However, it would be nice if there was some more Scala-friendly syntax of defining such Answer
.
Thank you.
I just found this blog post. It describes how to use implicit conversions to achieve what you want. If you define an implicit conversion like this
implicit def toAnswerWithArgs[T](f: InvocationOnMock => T) = new Answer[T] {
override def answer(i: InvocationOnMock): T = f(i)
}
you can call thenAnswer
with a simple function as argument:
when(mock.someMethodCall()).thenAnswer((i) => calculateReturnValue())
There is also a slightly shorter alternative version for the case when your mocked method has no arguments. Follow the link for details.
Define this helper function:
def answer[T](f: InvocationOnMock => T): Answer[T] = {
new Answer[T] {
override def answer(invocation: InvocationOnMock): T = f(invocation)
}
}
And use it like this, e.g. for returning a Future[MyClass]
containing any argument passed to a method:
when(myRepository.create(any[MyClass]())).thenAnswer(answer({ invocation =>
Future.successful(invocation.getArguments.head.asInstanceOf[MyClass])
}))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With