我有一个巨大的 json 对象,我需要解析它然后编写一些测试以查看是否一切都按预期进行。
case class User(id: Identification, age:Int, name: String ...)
case class Identification(id: Int, hash: String ....)
... a lot more classes
现在我正在尝试编写测试
val json = parse(Source.fromFile(/path).getLines.mkString("\n"))
import org.json4s.DefaultFormats
implicit val formats = DefaultFormats
所以我的问题是如何测试案例类是否正常? 我想也许我应该尝试为前任提取。用户,然后逐个检查参数是否正确,但我不认为这是一个好方法,因为创建 json 的不是我,所以我对内容不感兴趣。
谢谢
最佳答案
这是我在使用 JSON 和案例类时发现的,多年来公开了测试的最低限度。
这三件事应该经常测试
序列化与反序列化相结合
val example = MyCaseClass()
read[MyCaseClass](write(example)) should Equal example
检查一个类是否可以转换为 JSON,回读并仍然具有相同的值。这个坏掉的次数比人们想象的要多。
反序列化:JSON String
-> CaseClasses
val exampleAsJSON : String
val exampleAsCaseClass : MyCaseClass
read(exampleAsJSON) shouldEqual exampleAsCaseClass
检查 JSON 是否仍然可以反序列化。
序列化:CaseClasses
-> JSON String
val exampleAsJSON : String
val exampleAsCaseClass : MyCaseClass
write(exampleAsCaseClass) shouldEqual exampleAsJSON
检查字符串/JSON 表示是否保持稳定。在这里很难使数据保持最新,而且通常一些不太好的空白更改会导致误报。
其他要测试的东西
是否存在可选
参数?如果是,所有测试都应该在有和没有可选参数的情况下完成。
关于json - 如何使用 scala 中的 json4s 库测试我为解析器创建的案例类是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35826860/