Mockito Replies to ScalaTest

Is there an alternative to Mockito Answer in ScalaTest? I went through the documentation but found nothing.

For example, I would like to execute some logic on the arguments of the hatched 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 using Mockito. However, it would be nice if Scala also had friendly syntax for defining such an Answer .

Thanks.

+4
source share
4 answers

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 an argument:

 when(mock.someMethodCall()).thenAnswer((i) => calculateReturnValue()) 

There is also a slightly shorter alternative version for the case where your mocking method has no arguments. See the link for more details.

+5
source

If you mix the MockitoSugar tag, you can create a layout and pass it using this syntax:

 mock[Collaborator](new Answer(){ ... }) 
+2
source

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 that, for example. to return a Future[MyClass] containing any argument passed to the method:

 when(myRepository.create(any[MyClass]())).thenAnswer(answer({ invocation => Future.successful(invocation.getArguments.head.asInstanceOf[MyClass]) })) 
+2
source

Have you tried ScalaMock ? It is also integrated with ScalaTest and provides a more Scala-friendly API.

+1
source

All Articles