Choosing a Testing Style
Explore the different testing styles supported by ScalaTest.
How to choose a style
ScalaTest lets us choose a testing style. This means we can select one of its style traits, which, in turn, will drive the way we write our test cases. In this lesson, we’ll explore the available testing styles in ScalaTest. But the goal of such a wealth of testing styles is not to have developers use different styles in the same project. ScalaTest’s documentation advises choosing only one style for each project.
Tip: Always use different styles for different types of tests, such as unit tests and acceptance tests.
This makes sense; for unit tests, we’re mainly interested in verifying that a single component works, whereas in acceptance tests, we’re more focused on testing the high-level features of the project. Generally, we use the same style for unit and integration tests.
Before taking a look at the testing styles, let’s enrich our Author
class with some validation and a fullName
property, concatenating firstName
and lastName
.
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"
Using require
is not considered best practice because it throws an IllegalArgumentException
if the requirement fails.
Note: In Scala, it’s much better to use types (such as
Either
) to model something that might fail.
In this case, a better implementation would be to override the apply
method in the Author
companion object to return an Either
, with the right projection being the Author
instance and the left projection being some kind of error. However, we’ll use this basic implementation to show how exceptions are handled in ScalaTest style traits.
The FunSuite
style
The “fun” in FunSuite
stands ...