简体   繁体   中英

How to get ValidationError from JsResult in the test

I have this code to check list is empty or not, if it is empty, it will have ValidationError("should not empty")

case class Foo(t: List[String], r: String)

object Foo {
  implicit val fooReads: Reads[Foo] = (
  (JsPath \ "t").read[List[String]]
      .filter(ValidationError("should not empty"))(_.nonEmpty) and
    (JsPath \ "r").read[String]
  )
}

However, I dont know how to get the validation error in the test.

val json =  """
      |{
      |  "t": [],
      |  "r": "123"
      |}
    """.stripMargin
val result: JsResult[Foo] = json.validate[Foo]

result.isError shouldBe true
result.asEither.left.get.head._2.head.message shouldBe "should not empty"

The code is little ugly, is there a better way to test ValidationError from JsResult ?

Many thanks in advance

Unfortunately I don't think you'll be able to make the message-check any less verbose - it's a pretty complex structure you have to navigate.

Given that, my suggestion is to actually go the other way, and break out that huge chain of dereferences into some steps that can be more easily followed.

I've done this in Specs2 "Unit" style, but it would be simple to adapt:

result.isError must beTrue

val allErrors = result.asEither.left.get
allErrors must haveSize(1)

val firstBadNode = allErrors.head
firstBadNode._1 must beEqualTo(JsPath \ "t")

val badNodeErrors = firstBadNode._2
badNodeErrors must haveSize(1)
badNodeErrors.head.message must beEqualTo("should not empty")

If and when somebody refactors something and breaks your Reads[Foo] , this might save a bit of time fixing the broken test...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM