我已经创建了一个specs测试,以验证一些JSON解析。虽然测试效果很好,但感觉相当嘈杂。
我想知道规格中是否存在现有代码以取消选择和使用?
"twitter json to Scala class mapper" should {
"parsing a tweet" in {
TwitterJsonMapper.tweetP(tweetS) match {
case Right(t: Tweet) => {
implicit def unOption[T](t: Option[T]): T = t.get
implicit def unEither[T](t: Either[T,Throwable]): T = t match {case Left(left) => left ;case Right(t) => throw t}
"test id" in {
true must_== (t.id.get == 228106060337135617l)
}
"test id_str" in {
true must_== (t.id_str.get == "228106060337135617")
}
"test time" in {
true must_== (t.created_at.getHours == 13 )
}
}
case Left((pe: JsonParseException, reason: String)) => fail(reason + "\n" + pe)
}
}
}
//The Tweet is produced from JSON using Fasterxml's Jackson-Scala library.
//I want to use Option or Either monads over all child attributes - for the usual reasons.
case class Tweet(
@BeanProperty contributors: Option[String],
@BeanProperty coordinates: Option[String],
@BeanProperty @JsonDeserialize (
using = classOf[TwitterDateDeserializer]
) created_at: Either[Date,Throwable],
@BeanProperty favorited: Boolean = false,
//elided etc etc
@BeanProperty id_str: Option[String]
}
答案 0 :(得分:7)
Option
和Either
确实存在一些特定的匹配器:
t.id must beSome(228106060337135617l)
t.id_str must beSome("228106060337135617")
t.created_at.left.map(_.getHours) must beLeft(13)
答案 1 :(得分:2)
我还没有发现这是必要的。 Remeber,Option /要么具有价值平等。只需匹配Option / Either,而不是匹配它们包含的值。
"Option should match other options" >> {
Some(21) must be equalTo Some(21)
}
"Either should match Either" >> {
Right("Some string") must be equalTo Right("Some string")
}
我没有尝试编译这些,但它们应该可以工作。您可能需要添加一些明确的输入(或使用不属于安全的must_==
)
t.id must be equalTo Some(228106060337135617l)
t.id_str must be equalTo Some("228106060337135617")
t.created_at.left.map(_.getHours) must be equalTo Left(13)