Assertions
Explore how to use assertion functions in ScalaTest to verify conditions and validate code behavior. Understand assert, assertResult, and assertThrows, and learn to write clearer test cases with informative error messages and idiomatic Scala constructs.
We'll cover the following...
What is an assertion?
Assertions are basically functions we invoke to verify if a certain condition is true. We’ve already seen two types of these:
The
assertfunction lets us specify a condition that must be true.The
assertThrowfunction ensures a given exception is thrown during the execution of a block of code.
ScalaTest defines a third assertion function, assertResult, to specify more clearly the expected and actual value. It’s a short form of assert with an equality condition.
Assertions are also the most basic way to verify some conditions held in ScalaTest. They’re not very expressive and don’t enforce any human-readable way to write those conditions. Later in the course, we’ll meet matchers, a DSL to write more expressive tests. But for now, let’s get to know assertions.
Assertions are defined in the Assertions trait, which is extended by Suite. Therefore, all the testing styles have access to the assertion functions. Moreover, Assertions provides other interesting functions that we’ll explore in this lesson and some of the following ones.
Let’s move away from testing the authors’ full names and work on Course. In the examples that follow, we’ll be using a new ...