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

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

The Scala Cookbook

This tutorial is sponsored by the Scala Cookbook, which I wrote, and was published by O’Reilly in late 2013:

You can find the Scala Cookbook at these locations:

I hope it has been helpful. All the best, Al.

This website is a little one-man operation. If you found this information helpful, I’d appreciate it if you would share it.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Enter the characters shown in the image.