Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito's Answer in ScalaTest

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.

like image 824
semberal Avatar asked Feb 22 '13 12:02

semberal


2 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 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.

like image 161
lex82 Avatar answered Oct 21 '22 04:10

lex82


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])
}))
like image 39
Fernando Correia Avatar answered Oct 21 '22 02:10

Fernando Correia