Search code examples
scalaplayframeworkscalatestjson4sscalacheck

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


I have a function in my service that takes some jvalue data, extract it and return some model.

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

and in my test I want to call this function with bad data and see that the extraction fails. so I tried:

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

res shouldBe a[MappingException]

and it didn't work, because in my test class I'm injecting the service and using the service function, so the failure happens in the service and I'm not getting the error. I'm not even getting to res shouldBe a[MappingException], it fails when I call the function.

How do I do this right?


Solution

  • You can use thrownBy to store the exception:

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

    or check it directly:

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

    See the documentation for more details.