Search⌘ K

Unit Tests

Explore how to create unit tests for Scala HTTP APIs using functional programming. Learn to test database helpers and JSON codecs, including handling valid and invalid inputs and ensuring reversible encoding. This lesson helps build reliable and maintainable tests for pure and impure service components.

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.

Scala
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

Scala
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
...