How to show difference between what is given and expected in ScalaTest?
Asked Answered
F

2

11

If you match lists or maps or any other complex structures it's useful to see the difference between what is given and what expected. For example:

Map("a" -> 1, "b" -> 2, "c" -> 3) should equal Map("a" -> 1, "b" -> 5, "c" -> 3)

// ScalaTest output:
[info] Map("a" -> 1, "b" -> 2, "c" -> 3) did not equal Map("a" -> 1, "b" -> 5, "c" -> 3) (Test.scala)
[info]   org.scalatest.exceptions.TestFailedException:
[info]   ...

You would have to manually glance through both Maps to find the difference between them, the bigger your collection gets the harder it becomes.

In RSpec on the other hand you would get:

expect({a: 1, b: 2, c: 3}).to match({a: 1, b: 5, c: 3})

// RSpec output:
 Failure/Error: it { expect({a: 1, b: 2, c: 3}).to match({a: 1, b: 5, c: 3})}
   expected {:a=>1, :b=>2, :c=>3} to match {:a=>1, :b=>5, :c=>3}
   Diff:
   @@ -1,4 +1,4 @@
    :a => 1,
   -:b => 5,
   +:b => 2,
    :c => 3,

 # ./spec/test_spec.rb:2:in `block (2 levels) in <top (required)>'

Is it possible to have something similar with ScalaTest?

Furrow answered 15/2, 2015 at 17:17 Comment(0)
T
2

I don't believe there is anything exactly like you describe. The closest you may get in ScalaTest is the built-in diffing for String.

It's not ideal, but adding toString on the end of your maps will give a slightly better output. Similarly, using the pretty method on org.scalautils.PrettyMethods does the same thing.

For example:

Map("a" -> 1, "b" -> 2, "c" -> 3).toString shouldBe Map("a" -> 1, "b" -> 5, "c" -> 3).toString

// scalatest output
[info] "Map(a -> 1, b -> [2], c -> 3)" was not equal to "Map(a -> 1, b -> [5], c -> 3)"
[info] org.scalatest.exceptions.TestFailedException: ...

This scalatest-users email thread asks a similar question to yours, and has responses by Bill Venners, the author of ScalaTest.

Tractile answered 15/2, 2015 at 18:19 Comment(1)
I wonder if ScalaTest 3.0 (now in snapshot phase) would provide improvements to this. A video here -> skillsmatter.com/skillscasts/6021-scalatest-and-scalactic-3-0Sherrellsherrer
W
0

If you are using Scala test you might like to try diffx https://diffx-scala.readthedocs.io/en/latest/ it helped me debug few large test cases.

Woolsey answered 27/6, 2021 at 10:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.