Unit Tests

Learn how to implement a base class and tests for unit testing.

Base class for unit tests

To avoid repeating the construction of our unit test classes, we will implement a base class for tests, which is quite simple.

Press + to interact
abstract class BaseSpec extends WordSpec
with MustMatchers with ScalaCheckPropertyChecks {}

We will be leaning towards the more verbose test styles, but we can essentially use any of the other test styles that ScalaTest offers.

Testing Product fromDatabase

Press + to interact
import com.wegtam.books.pfhais.impure.models.TypeGenerators._
forAll("input") { p: Product =>
val rows = p.names.map(t => (p.id, t.lang.value, t.name.value)).toList
Product.fromDatabase(rows) must contain(p)
}

The code above is a straightforward test of our helper function fromDatabase, which works in the following way:

  1. The forAll will generate a lot of Product entities using the generator (Line 3).
  2. From each entity, a list of “rows” is constructed as they would appear in the database (Line 4).
  3. These constructed rows are given to the fromDatabase function (Line 5).
  4. The returned Option must then contain the
...