1. Introduction

In this tutorial, we are going to look into Behavior Driven Development (BDD) testing with Scala.

2. Setup

The library we’ll use in this article is ScalaTest. We’ll add it as a libraryDependency in our build.sbt file:

libraryDependencies += "org.scalatest" %% "scalatest" % "3.2.15"

3. Given, When, Then

BDD was developed to provide a common language between all members of a software project. It provides a standard for using plain language that describes the way software should behave.

When describing how the development of a user story should occur, we use three scenarios:

  • Given [a starting state]
  • When [an action is performed]
  • Then [a definable outcome is achieved]

Let’s say we want to write a test for a basic bank account that has a balance that can be incremented:

  • Given the bank account has a balance of $30
  • When $40 is added to the account balance
  • Then there should be $70 in the account

4. BDD Testing with ScalaTest

ScalaTest is a widely used testing library for Scala, Scala.js, and Java projects. It provides basic unit testing capability as well as an expressive BDD DSL.

First, we’ll extend the AnyFunSpec and GivenWhenThen traits to get the describe and given, when, then language we need for our test.

Let’s import the traits we will need:

import org.scalatest.GivenWhenThen
import org.scalatest.funspec.AnyFunSpec

Then we’ll describe what should happen to the bank account and execute the appropriate code after each description.

class BBDBankTest extends AnyFunSpec with GivenWhenThen {

  describe("A bank account") {

    it("should have money deposited into it") {

      Given("the bank account has a balance of $30")
      val bankAccount = new BankAccount(30)

      When("$40 is added to the account balance")
      bankAccount.addToBalance(40)

      Then("there should be $70 in the account")
      assert(bankAccount.balance == 70)
    }
  }
}

5. Conclusion

In this brief article, we looked at how to start BDD testing with Scala using the ScalaTest library. As always, the code is over on GitHub.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.