...

/

Handling Exceptions and Compilation Errors

Handling Exceptions and Compilation Errors

Learn how to write tests for exceptions and compilation errors.

Exceptions and compilation errors

So far, we haven’t considered exceptions or compilation errors in our tests.

Note: Scala code should throw as few exceptions as possible and treat errors as types as much as possible.

When writing a Scala application, we might find ourselves working with a Java library that uses a lot of exceptions. Our code will have to deal with them, and our tests have to make sure no exception will break our application.

In this lesson, we’ll take a look at how we can formulate assertions over thrown exceptions in ScalaTest. Additionally, we’ll see how to ensure that a snippet of code compiles or doesn’t compile. This is very useful when we write a DSL or a library. In this lesson, we’ll use the following validation based on require in Author:

Press + to interact
case class Author(firstName: String, lastName: String):
require(!firstName.isBlank, "The first name must not be blank")
require(!lastName.isBlank, "The last name must not be blank")
val fullName: String = s"$firstName $lastName"

Assertions on exceptions

The most basic way to check whether a snippet of code throws an ...