Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

FlatSpec

ScalaTest is a versatile testing library in Scala that supports different testing styles, making it adaptable to various testing needs. Here's a basic tutorial on how to get started with ScalaTest, covering setup, writing tests, and running them.

Setting Up

To use ScalaTest, you need to add it as a dependency in your build tool configuration. If you're using sbt, add the following to your build.sbt:

libraryDependencies += "org.scalatest" %% "scalatest" % "3.2.9" % Test

Ensure you're using the latest version of ScalaTest by checking the ScalaTest website.

Writing Tests

ScalaTest supports multiple testing styles. We'll use the FlatSpec style for this tutorial, which is a good choice for behavior-driven development (BDD).

Create a Scala class or object for the component you want to test. Here's a simple example:

object Calculator {
  def add(a: Int, b: Int): Int = a + b
}

Now, create a test class in your src/test/scala directory. Here's how you might test the Calculator object:

import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

class CalculatorSpec extends AnyFlatSpec with Matchers {

  "The Calculator" should "add two numbers correctly" in {
    Calculator.add(2, 3) should be (5)
  }

  it should "add negative numbers correctly" in {
    Calculator.add(-1, -1) should be (-2)
  }

  it should "add a number to zero correctly" in {
    Calculator.add(0, 5) should be (5)
  }
}

Running Tests

If you're using sbt, you can run your tests from the terminal with the following command:

sbt test

This command will compile your test classes and run all tests, reporting the results in the terminal.

Understanding the Test Code

  • AnyFlatSpec: This is a base class for writing tests in a "flat" specification style. You describe behaviors and write tests for each behavior.
  • Matchers: This trait provides a domain-specific language (DSL) for expressing assertions about values in your tests. For example, should be is part of this DSL.
  • "The Calculator" should "add two numbers correctly" in: This syntax describes a behavior and a test scenario. The block following in contains the test code for that scenario.

Further Testing Capabilities

ScalaTest offers much more than simple assertions:

  • ScalaTest with ScalaCheck: For property-based testing, ScalaTest can be integrated with ScalaCheck to automatically generate test cases.
  • Asynchronous Testing: ScalaTest supports testing asynchronous code, making it easier to test Futures and other async operations.
  • Before and After Hooks: ScalaTest provides BeforeAndAfter and BeforeAndAfterEach traits that you can mix into your test classes to set up preconditions or clean up after your tests.