scala - 测试 Right[Seq[MyClass]] 和属性

标签 scala testing scalatest

我正在尝试使用 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/

相关文章:

scala - 具有最大位数的字符串格式

scala - 确定 Scala 类中 Option 字段的类型

scala - Scala 中的 BDD - 它必须是丑陋的吗?

没有夹具的ScalaTest测试名称?

Scala 比较泛型?

scala - 小版本更新可以用来小更新传递依赖吗?

java - 排除Spring boot测试中的Configuration

security - 如何在 Web 应用程序中操作 View 状态数据?

reactjs - TypeError : document. createElement 不是函数 - React、Mocha、JSDOM 测试

scala - 使用命令行参数运行 SBT 任务