ScalaTest 106: Printing expected and actual values when a test fails

Scala Problem: You’d like to have better output from your ScalaTest assert tests, output that shows the expected and actual values.


One approach is to use the === method instead of ==. When an assert test fails, the === method output shows the two values from the test.

This can be demonstrated by putting an intentional error into a unit test while using ===. Here’s a modified version of a TDD test method with an intentional error:

test("new pizza has zero toppings (version 2)") {
  // intentional error here; size should be 0
  assert(pizza.getToppings.size === 1)

Adding this test to the TDD test class introduced in Writing TDD Tests with ScalaTest results in the following output:

[info] PizzaTests:
[info] - new pizza has zero toppings (version 2) *** FAILED ***
[info]   0 did not equal 1 (PizzaTests.scala:18)

Using === informs you that “0 did not equal 1,” and gives you the line number of the failure.

Another approach is to use expectResult instead of assert:

test("new pizza has zero toppings (version 3)") {
  // `expectResult` is now `assertResult`
  // expectResult(1) {
  assertResult(1) {

Although it’s a little more verbose, it gives more meaningful output, indicating what value was expected and what was actually found:

[info] PizzaTests:
[info] - new pizza has zero toppings (version 3) *** FAILED ***
[info]   Expected 1, but got 0 (PizzaTests.scala:19)

Both approaches are simple, and extremely helpful when debugging why a test failed. Use whichever you prefer, or both.

See Also