Alban Dericbourg
Alban Dericbourg

Reputation: 1636

Verify method call with implicit default value

I'd like to understand some behavior using Mockito and Scala's default parameters.

Here is a minimal example:

trait SomeImplicit

object SomeService {
  val AnyImplicit = new SomeImplicit {}
}

trait SomeService {
  def doWork(param: String)(implicit di: SomeImplicit = SomeService.AnyImplicit)
}

Let's call the doWork method:

class SomeService$Test extends WordSpec with MockitoSugar {
  "SomeService" should {
    "doWork" in {
      val dodo = mock[SomeService]
      val expectedParameter = "ok"

      dodo.doWork(expectedParameter)

      verify(dodo, times(1)).doWork(expectedParameter)(SomeService.AnyImplicit)
      verifyNoMoreInteractions(dodo)
    }
  }
}

Spontaneously, I'd have though it would work. But is does not. I get:

Argument(s) are different! Wanted:
someService.doWork(
    "ok",
    SomeService$$anon$1@264c1c97
);
-> at SomeService$Test$$anonfun$1$$anonfun$apply$mcV$sp$1.apply$mcV$sp(SomeService$Test.scala:25)
Actual invocation has different arguments:
someService.doWork(
    "ok",
    null
);
-> at SomeService$Test$$anonfun$1$$anonfun$apply$mcV$sp$1.apply$mcV$sp(SomeService$Test.scala:23)

Argument(s) are different! Wanted:
someService.doWork(
    "ok",
    SomeService$$anon$1@264c1c97
);
-> at SomeService$Test$$anonfun$1$$anonfun$apply$mcV$sp$1.apply$mcV$sp(SomeService$Test.scala:25)
Actual invocation has different arguments:
someService.doWork(
    "ok",
    null
);
-> at SomeService$Test$$anonfun$1$$anonfun$apply$mcV$sp$1.apply$mcV$sp(SomeService$Test.scala:23)

Upvotes: 2

Views: 320

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170723

An implicit parameter with a default value tells the compiler: if the implicit is not found by the usual implicit search process, use this value instead of emitting a compilation error.

DummyImplicit is always found in the first step (using Predef.dummyImplicit), so the default value is never used.

Upvotes: 1

Related Questions