Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 801
Andrew Avatar asked Feb 15 '15 17:02

Andrew


People also ask

How do you ignore test cases in ScalaTest?

It has been inserted into Scaladoc by pretending it is a trait. When you mark a test class with a tag annotation, ScalaTest will mark each test defined in that class with that tag. Thus, marking the SetSpec in the above example with the @Ignore tag annotation means that both tests in the class will be ignored.

What is Scalactic?

Scalactic provides a powerful === operator (and its complement, !== ) that allows you to. Customize equality for a type outside its class. Get compiler errors for suspicious equality comparisons. Compare numeric values for equality with a tolerance. Normalize values before comparing them for equality.

What is FunSuite in Scala?

A suite of tests in which each test is represented as a function value. The “ Fun ” in FunSuite stands for “function.” Here's an example FunSuite : import org.scalatest.FunSuite.


1 Answers

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.

like image 53
colinjwebb Avatar answered Oct 29 '22 16:10

colinjwebb