Search code examples
scalamockitospecs2

How to verify the type of an exception passed to a mock function?


In my code, there is:

def submitContent(getDocContent: () => String, callback: Try[Boolean] => Unit): Unit = {
    // ....
    callback(Failure(new InflightChangeTimeoutException(pendingChange)))
}

I want to test in some condition, the callback will be invoked with a Failure of some InflightChangeTimeoutException, but I dont' care what the value of the exception is.

In my speces2 test, I tryied:

val callback = mock[Try[Boolean] => Unit]

submitContent(() => "any-other", callback)

there was one(callback).apply(===(Failure(any[InflightChangeTimeoutException])))

Will give me some error like:

The mock was not called as expected: 
Argument(s) are different! Wanted:
function1.apply(
    'Failure(com.test.InflightChangeTimeoutException)'

 is not equal to 

'Failure(null)'
);

Not sure where is wrong. How to fix it?


Solution

  • any[A] is a function which registers a matcher for parameters to a mocked function as a side-effect. But the return value of any[A] is effectively null.

    So the proper way to check the result of the callback is:

    there was one(callback).apply(beLike[Failure[Boolean]] { case Failure(t) => 
      t must beAnInstanceOf[InflightChangeTimeoutException] 
    })