Search code examples
scalaspecs2scalacheck

Specs2 + Scalacheck Generate Tuple with different Strings


I have to test an loop-free graph and always checking whether the Strings are different is not very usable (it throws an exception). There must be a better solution, but I am not able to come up with it, and i am kind of lost in the specs2 documentation. This is an example of the code:

"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)
}

if a and c are the same, createDirectedEdge will throw an exception (i have different test for that behaviour).


Solution

  • Yep, there's a better way—this is precisely what conditional properties are for. Just add your condition followed by ==>:

    "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)
      }
    }
    

    If the condition is likely to fail often, you should probably take a different approach (see the ScalaCheck guide for details), but in your case a conditional property is totally appropriate.