Question

When verifying expected value of the scala collection, assertResult method is convenient:

"The list" should "be generated correctly" in {
  assertResult(List(10, 20)) {
    //Some code that should output 
    List(10, 20)
  }
}

If something goes wrong, nice error message is generated:

Expected List(10, 20), but got List(10, 30)

Unfortunately, it doesn't work for arrays, because == operator checks identity, not equality (The reasons behind this behaviour had been discussed a lot, for example here: Why doesn't Array's == function return true for Array(1,2) == Array(1,2)?).

So, similar check for arrays generates following error message:

Expected Array(10, 20), but got Array(10, 20) 

Of cause, it's possible to use should equal matcher:

"The array" should "be generated correctly" in {
  Array(10, 20) should equal {
    //Some code that should output 
    Array(10, 20)
  }
}

But IMO it's less convenient, since it's more an equality check that an expectation verification:

Array(10, 20) did not equal Array(10, 30)

Is there an assertion check for arrays in ScalaTest that clearly separates expected result from actual result?

Was it helpful?

Solution

Wow, well I actually consider that a bug, because it is inconsistent with the rest of the assertions. This bug has lived undetected for about six or seven years, though. I'll fix it, but what you can do in the meantime is call .deep. That's what you'd do for == with Arrays, for example:

scala> Array(1, 2) == Array(1, 2)
res12: Boolean = false

scala> Array(1, 2).deep == Array(1, 2).deep
res13: Boolean = true

scala> assertResult(Array(1, 2)) { Array(1, 2) }
org.scalatest.exceptions.TestFailedException: Expected Array(1, 2), but got Array(1, 2)
...

scala> assertResult(Array(1, 2).deep) { Array(1, 2).deep }

OTHER TIPS

You could use .seq method on Array to wrap it with WrappedArray like this:

assertResult(Array(10, 20).seq){Array(10, 20).seq}

Array#equals implemented as reference equality:

Array(10, 20) == Array(10, 20)
// Boolean = false

WrappedArray#equals implemented as elements equality:

Array(10, 20).seq == Array(10, 20).seq
// Boolean = true
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top