I'm trying to port a Scala system to Mockito2. There are a few test cases that use doReturn
and now in Mockito 2.18.0
I get this error:
Error:(34, 5) ambiguous reference to overloaded definition,
both method doReturn in object Mockito of type (x$1: Any, x$2: Object*)org.mockito.stubbing.Stubber
and method doReturn in object Mockito of type (x$1: Any)org.mockito.stubbing.Stubber
match argument types (com.twitter.util.Future[Unit])
doReturn(Future.Unit).when(f.adapterSpy).myFunction(userData, Some(offerId), Always)
Looking in Mockito.java
, doReturn
is really overloaded like that:
public static Stubber doReturn(Object toBeReturned)
public static Stubber doReturn(Object toBeReturned, Object... toBeReturnedNext)
How on Earth is this not always ambiguous? How do I make it compile?
Thanks
This can also be overcome by using doAnswer
instead of doReturn
// no good
doReturn(true).when(foo).bar()
// works
doAnswer(_ => true).when(foo).bar()
As a temporary workaround, you can do the following:
trait MockitoHelper extends MockitoSugar {
def doReturn(toBeReturned: Any): Stubber = {
Mockito.doReturn(toBeReturned, Nil: _*)
}
}
Then have your test mixin this MockitoHelper
.
There is a ticket in the Scala backlog on it. see https://github.com/scala/bug/issues/4775
This is a bit of self promotion but I just published a library called mockito-scala
that solves this issue and many more, is part of the mockito ecosystem so hopefully should become the default when working with Scala, you can find it here https://github.com/mockito/mockito-scala with the information to get the dependency and what problems does it actually solves.
Specifically for your problem, you could write this code and it would work out of the box
doReturn(Future.successful(())).when(f.adapterSpy).myFunction(userData, Some(offerId), Always)
I changed the way the future is expressed just because is the correct way to create a completed future of Unit
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