Suppose I have this class:
class Defaults { def doSomething(regular: String, default: Option[String] = None) = { println(s"Doing something: $regular, $default") } }
I want to verify that some other class calls the doSomething() method on the Defaults instance without passing a second argument:
defaults.doSomething("abcd") // second argument is None implicitly
However, the mocking Defaults class does not work correctly. Since the default values ββfor the method arguments are compiled as hidden methods in the same class, mock[Defaults] returns an object in which these hidden methods return null instead of None , so this test fails:
class Test extends FreeSpec with ShouldMatchers with MockitoSugar { "Defaults" - { "should be called with default argument" in { val d = mock[Defaults] d.doSomething("abcd") verify(d).doSomething("abcd", None) } } }
Mistake:
Argument(s) are different! Wanted: defaults.doSomething("abcd", None); -> at defaults.Test$$anonfun$1$$anonfun$apply$mcV$sp$1.apply$mcV$sp(Test.scala:14) Actual invocation has different arguments: defaults.doSomething("abcd", null); -> at defaults.Test$$anonfun$1$$anonfun$apply$mcV$sp$1.apply$mcV$sp(Test.scala:12)
The reason for this is clear, but is there a reasonable workaround? The only thing I see is to use spy() instead of mock() , but my mocking class contains many methods that I will have to mock explicitly in this case, and I don't want this.
scala mockito default-arguments
Vladimir Matveev
source share