如何为Play Framework JSON读者编写单元测试

时间:2016-06-08 14:38:27

标签: scala playframework

我希望为shipmentNumberValidator方法编写单元测试,其中Readsplay.api.libs.json.Reads。我该怎么做?

object Validator {
    def shipmentNumberValidator(): Reads[String] =
        Reads.filter(ValidationError(ErrorConstants.BAD_SHIPMENT_NUMBER))(_.matches(BarcodePatterns.ShipmentNumber))
}

单元测试应向其传递货件编号,并且该方法成功返回货件编号,或者如果货件编号格式不匹配则返回错误消息。我不知道如何将值传递给此方法。

该方法通常用于伴随对象以进行隐式读取,例如:

object ShipmentOrder {
    implicit val shipmentOrderReads: Reads[ShipmentOrder] = (
  (JsPath \ "id").read[String](Validator.missingFieldValidator("id") keepAnd Validator.shipmentNumberValidator())(ShipmentOrder.apply _)
}

1 个答案:

答案 0 :(得分:3)

根据您使用的test framework(例如specs2),您可以按以下方式测试预期:

  • 执行Json.parse("{expectedJson}") must be JsResult(expectedInstance)
  • 执行Json.parse("{unexpectedJson}") must be JsError(_)

使用specs2:

import play.api.libs.json._

"JSON" should {
  "be successfully parsed when expected" in {
    Json.parse("""{"expected":"json"}""") must beLike[JsResult[ShipmentOrder]] {
      case JsSuccess(parsed, _) =>
        parsed must_== expectedShipmentOrder
    }
  }

  "fail to be parsed if expected" in {
    Json.parse("""{"unexpected":"json"}""") must beLike[JsResult[ShipmentOrder]] {
      case JsError(details) =>
        ok // possible check `details`
    }
  }
}