我正在尝试使用 ScalaTest (WordSpecLike
, MustMatchers
) 进行测试,以验证 Either[Seq[Error], Seq[Value]]
包含一个值,如果该值具有某些特定属性。
理想情况下我想要这样的东西:
val result:Either[Seq[Error], Seq[Value]] = ...
result.value must contain { _ have (
'prop ("value")
)}
但这不会编译,我不知道如何实现这种匹配。
是否有关于深度测试或一些最佳实践的文档?
最佳答案
Inspectors
启用关于集合的断言,并结合 EitherValues
,正如@LuisMiguelMejíaSuárez 和 checking arbitrary properties with have
所建议的那样, 下面的语法是可能的
atLeast(1, result.right.value) must have ('prop ("value"))
这是一个工作示例
class Value(val foo: String, val bar: Int) {
def isTooLong: Boolean = foo.length > 2
}
class StackOverflowSpec extends WordSpec with MustMatchers with EitherValues with Inspectors {
"Result" when {
"Right" should {
"have property" in {
val result: Either[Seq[Error], Seq[Value]] = Right(Seq(new Value("aa", 11), new Value("bbb", 42)))
atLeast(1, result.right.value) must have ('tooLong (true), 'bar (42) )
}
}
}
}
或者尝试对结果进行模式匹配并将属性谓词传递给 Seq.exists
像这样
class Value(val foo: String, val bar: String) {
def isTooLong: Boolean = foo.length > 2
}
class StackOverflowSpec extends WordSpec with MustMatchers {
"Result" when {
"Right" should {
"have property" in {
val result: Either[Seq[Error], Seq[Value]] = Right(Seq(new Value("a", "b"), new Value("ccc", "ddd")))
result match {
case Left(seq) => fail
case Right(seq) => seq.exists(_.isTooLong) must be(true)
}
}
}
}
}
关于scala - 测试 Right[Seq[MyClass]] 和属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56560495/