Scala 测试问题 [英] Scala test issues
问题描述
我是 Scala 的新手,使用 Scala 测试和喷雾 json 编写测试用例.我的代码如下:
I am new to Scala and writing test cases using Scala test and spray json. My code is as follows:
case class MyModel(Point1: String,
Point2: String,
Point3: Option[NewModel] = None)
case class NewModel(Point4: Boolean,
Point5: Boolean,
Point6: Boolean)
it should "serialise/deserialize a MyModel to JSON" in {
val json= """{"Point1":"","Point3":[],"Point2":""}""".parseJson
val myModelViaJson= json.convertTo[MyModel]
myModelViaJson.Point1 shouldBe ""
myModelViaJson.Point3.head.point4 shouldBe true
myModelViaJson.Point2 shouldBe ""
}
我在运行测试用例时遇到以下错误
I am getting following error on running test case
should serialise/deserialize a MyModel to JSON *** FAILED ***
[info] spray.json.DeserializationException: Object expected in field 'point4'
[info] at spray.json.package$.deserializationError(package.scala:23)
[info] at spray.json.ProductFormats.fromField(ProductFormats.scala:63)
[info] at spray.json.ProductFormats.fromField$(ProductFormats.scala:51)
如何解决这个问题?
推荐答案
您的 JSON 将 Point3
的值设置为 []
,这是一个空数组,但在Scala 它应该是一个 NewModel
对象(因此是Object expected").
Your JSON sets the value of Point3
to []
which is an empty array, but in the Scala it should be a NewModel
object (hence "Object expected").
在 MyModel
中使用 Option
表示 JSON 中可能缺少该字段,在这种情况下,提取的值将为 None
.如果 Point3
字段存在于 JSON 中,它应该包含 NewModel
的 JSON,然后该字段将是 Some(
The use of Option
in MyModel
says that the field might be missing from the JSON, in which case the extracted value will be None
. If the Point3
field is present in the JSON, it should contain the JSON for a NewModel
, and the field will then be Some(<NewModel instance>)
.
这篇关于Scala 测试问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!