给定代数数据类型
sealed trait Result
case object Success extends Result
case class MyFailure(details: String) extends Result
如何断言zio-test
该特定值是 aFailure
并且它的详细信息包含特定的子字符串?
例如,如何断言下面r
是失败并带有"mana"
子字符串?
val r: Result = MyFailure("not enough mana")
给定代数数据类型
sealed trait Result
case object Success extends Result
case class MyFailure(details: String) extends Result
如何断言zio-test
该特定值是 aFailure
并且它的详细信息包含特定的子字符串?
例如,如何断言下面r
是失败并带有"mana"
子字符串?
val r: Result = MyFailure("not enough mana")
假设结果是由一个 effect 产生的(换句话说,它被 ZIO 包装了),你可以在失败mapError
的情况下使用 to ,然后使用anddetails
有效地断言:assertM
fails(containsString)
testM("effectfully") {
val r = ZIO.fail(MyFailure("not enough mana")).mapError(_.details)
assertM(r.run)(fails(containsString("mana")))
}
这是可能的isCase
剪辑:
/**
* Makes a new assertion that requires the sum type be a specified term.
*
* {{{
* isCase("Some", Some.unapply, anything)
* }}}
*/
def isCase[Sum, Proj](
termName: String,
term: Sum => Option[Proj],
assertion: Assertion[Proj]
)
而我的(可能不是理想的)解决方案:
sealed trait Result
case object Success extends Result
case class MyFailure(details: String) extends Result
val r: Result = MyFailure("not enought mana")
test("mana") {
assert(r)(
isCase[Result, String](
"details",
{
case MyFailure(details) => Some(details)
case _ => None
},
containsString("mana"))
)
}
或者,可以创建一个辅助函数并将其用于这种情况:
def matches[A](mf: PartialFunction[A, Boolean]): Assertion[A] =
Assertion.assertion("matches")() {
a => mf.orElse[A, Boolean]({ case _ => false })(a)
}
现在测试可能如下所示:
assert(r)(
matches {
case MyFailure(d) => d.contains("mana")
}
)