scalatest 使用包含 allElementsOf 和 A​​rrayBuffers

scalatest using contains allElementsOf with ArrayBuffers

我一直在处理一些 XML 数据,并且一直在尝试编写一个测试来匹配两棵 xml 树的直接子节点具有所有相同类型的节点 bar.

我开始使用一个简单的测试来确保两个数据结构匹配。

将它们匹配为字符串的断言有效:

result.toString should be(expected.toString)

但是匹配每个单独元素的断言失败:

result should contain allElementsOf expected

我在这个 answer here

上找到的

因为这些更简单的断言不起作用:

result should be(expected)
result should contain(expected(1))

测试在测试 class:

中使用 before 块设置 XML
  var foo: Elem = _

  before {
   foo = <foo>
     <bar type="greet" style="pleasent" target="anyone">hi</bar>
     <bar type="count">1</bar>
     <bar type="color">yellow</bar>
     <baz>
      <bar type="bad">Bad</bar>
    </baz>
  </foo>
}

这是测试代码:

it should "allow use of map and filter" in {
  import scala.collection.mutable.ArrayBuffer

  val expected = ArrayBuffer(
    (
      "bar",
      Map(
        "type" -> "greet",
        "style" -> "pleasent",
        "target" -> "anyone"
      ),
      "hi"
    ),
    (
      "bar",
      Map("type" -> "count"),
      "1"
    ),
    (
      "bar",
      Map("type" -> "color"),
      "yellow"
    )
  )

  val result = foo.child.map(x => {
    x match {
      case <bar>{text}</bar> => (x.label, x.attributes.asAttrMap, text)
      case <baz>_</baz> => (x.label, Map[String,String](), "")
      case _ => ("", Map[String,String](), "")
    }
  })
  .filter(x => {
    x match {
      case ("bar", _, _) => true
      case _ => false
    }
  })


  result.toString should be(expected.toString) // works
 // result should contain allElementsOf expected // fails

}

您比较的集合中的元素类型不同:

  • result 包含 (String, Map[String, String], Object)
  • 类型的元素
  • expected 包含 (String, Map[String, String], String)
  • 类型的元素

它们可能具有相同的 toString 表示,但这并不意味着它们是平等的。 result 的类型可能不是您期望的这种模式匹配的类型:

x match {
  case <bar>{text}</bar> => (x.label, x.attributes.asAttrMap, text)
  case <baz>_</baz> => (x.label, Map[String,String](), "")
  case _ => ("", Map[String,String](), "")
}

这里text是类型xml.Node。如果你想提取节点的内容,你可以使用 text.text 这也使测试通过。

旁白:最近有一个合并到 Scala 的 PR 在推断 Object 类型时发出警告(scala/scala#6178),因为这通常是程序员错误。