检查的异常对于此方法无效错误

Checked exception is invalid for this method Error

据我所知,Scala 没有检查异常,即我不需要指定方法将抛出的异常。

我正在测试 class a 的方法 A。它调用 class b 的方法 B。我想测试 B 抛出异常时的行为。

class b{
    def B()={...}
}

我嘲笑过B

when(mockB.B).thenThrow(new UserDoesNotExistException("exception"))

当我这样做时,出现错误 Checked exception is invalid for this method!

这个答案解释了 w.r.t。 Java - 使用 Mockito 从模拟中抛出已检查的异常

虽然将 UserDoesNotExistException 更改为 RuntimeException 对我有用,但我很想知道我是否可以通过抛出 UserDoesNotExistException

来进行测试

在我的逻辑中,A 有不同的路径,具体取决于抛出的异常类型,因此我需要从我的测试中抛出特定的异常,而不是抛出通用的 RuntimeException.

简短的回答是可以。你怎么能那样做? B方法需要添加throws注解:

class b{
    @throws(classOf[UserDoesNotExistException])
    def B()={...}
}

根据 Scala Cookbook 关于抛出注释:

First, whether the consumers are using Scala or Java, if they’re writing robust code, they’ll want to know that something failed. Second, if they’re using Java, the @throws annotation is the Scala way of providing the throws method signature to Java consumers.

既然Mockito.java是写在java中的,它就得知道哪些用户异常可以抛出。 RuntimeException,不应该显式写,因为它总是可以抛出。

另一种可能的解决方案,是升级到最新的mockito-scala(目前是1.15.0版本),您可以使用:

org.mockito.MockitoSugar.when

这是纯 scala,然后下面的代码应该可以工作:

import org.mockito.MockitoSugar.{mock, when}
val bMock = mock[b]
when(bMock.B()).thenThrow(new UserDoesNotExistException("exception"))

thenAnswer 也有效 -

when(mockB.B).thenAnswer(invocation=>throw new UserDoesNotExistException("exception"))