我想了解使用Mockito和Scala默认参数的一些行为。
这是一个最小的例子:
trait SomeImplicit
object SomeService {
val AnyImplicit = new SomeImplicit {}
}
trait SomeService {
def doWork(param: String)(implicit di: SomeImplicit = SomeService.AnyImplicit)
}
让我们调用doWork
方法:
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)
}
}
}
自然而然地,虽然它会起作用但是我会这样做。但事实并非如此。我明白了:
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)
答案 0 :(得分:1)
带有默认值的隐式参数告诉编译器:如果通常的隐式搜索过程找不到隐式参数,请使用此值而不是发出编译错误。
始终在第一步中找到 DummyImplicit
(使用Predef.dummyImplicit
),因此永远不会使用默认值。