我希望为shipmentNumberValidator
方法编写单元测试,其中Reads
为play.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 _)
}
答案 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`
}
}
}