Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito doReturn: ambiguous reference to overloaded definition

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

like image 339
tjarvstrand Avatar asked May 30 '18 08:05

tjarvstrand


4 Answers

This can also be overcome by using doAnswer instead of doReturn

// no good
doReturn(true).when(foo).bar()
// works
doAnswer(_ => true).when(foo).bar()
like image 72
Jaxsun Avatar answered Nov 14 '22 01:11

Jaxsun


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.

like image 40
ssgao Avatar answered Nov 14 '22 00:11

ssgao


There is a ticket in the Scala backlog on it. see https://github.com/scala/bug/issues/4775

like image 9
reikje Avatar answered Nov 14 '22 00:11

reikje


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

like image 1
Bruno Avatar answered Nov 14 '22 01:11

Bruno