如何验证传递给模拟函数的异常类型?

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

在我的代码中,有:

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

我想在某些情况下进行测试,callback 将被某些 InflightChangeTimeoutExceptionFailure 调用,但我不关心异常的值是什么。

在我的 speces2 测试中,我尝试了:

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

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

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

会给我一些错误,例如:

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

 is not equal to 

'Failure(null)'
);

不知道哪里错了。如何解决?

any[A] 是一个函数,它将参数的匹配器注册到模拟函数作为副作用。但是 any[A] 的 return 值实际上是 null

所以检查回调结果的正确方法是:

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