如何在我的测试中获取另一个 class 范围内发生的故障?

How to get the failure that happens in another class scope in my test?

我的服务中有一个函数可以获取一些 jvalue 数据,将其提取并 return 一些模型。

def getInstanceOf(data: JValue, aType: String): Living = aType match {
    case "person" => data.extract[Person]
    case "animal" => data.extract[Animal]
}

在我的测试中,我想用错误的数据调用这个函数,然后看到提取失败。所以我尝试了:

val res = myService.getInstanceOf(badData, "person")

res shouldBe a[MappingException]

它没有用,因为在我的测试中 class 我正在注入服务并使用服务功能,所以服务中发生了故障,我没有收到错误。我什至没有到达 res shouldBe a[MappingException],当我调用该函数时它失败了。

我该怎么做才对?

以下应该有效

import scala.util.{Failure, Try}
val Failure(th) = Try(myService.getInstanceOf(badData, "person"))
res shouldBe a[MappingException]

您可以使用thrownBy来存储异常:

val res = the [MappingException] thrownBy myService.getInstanceOf(badData, "person")

或直接查看:

a [MappingException] should be thrownBy myService.getInstanceOf(badData, "person")

有关详细信息,请参阅 documentation