Specs2 + Scalacheck 生成不同字符串的元组

Specs2 + Scalacheck Generate Tuple with different Strings

我必须测试一个无环图并且总是检查字符串是否不同不是很有用(它会抛出异常)。一定有更好的解决方案,但我无法想出它,而且我有点迷失在 specs2 文档中。 这是代码示例:

"BiDirectionalEdge" should {
"throw an Error for the wrong DirectedEdges" in prop {
  (a :String, b :String, c :String, d :String) =>
    val edge1 = createDirectedEdge(a, b, c)
    val edge2 = createDirectedEdge(c, b, d)
    new BiDirectionalEdge(edge1, edge2) must throwA[InvalidFormatException] or(a mustEqual d)
}

如果 a 和 c 相同,createDirectedEdge 将抛出异常(我对该行为有不同的测试)。

是的,有更好的方法 - 这正是条件属性的用途。只需添加您的条件,然后添加 ==>:

"BiDirectionalEdge" should {
  "throw an Error for the wrong DirectedEdges" in prop {
    (a: String, b: String, c: String, d: String) => (a != c) ==>
      val edge1 = createDirectedEdge(a, b, c)
      val edge2 = createDirectedEdge(c, b, d)
      new BiDirectionalEdge(edge1, edge2) must
        throwA[InvalidFormatException] or(a mustEqual d)
  }
}

如果条件可能经常失败,您可能应该采取不同的方法(有关详细信息,请参阅 the ScalaCheck guide),但在您的情况下,条件 属性 是完全合适的。