
Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: March 18, 2024
In this tutorial, we are going to look into Behavior Driven Development (BDD) testing with Scala.
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"
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:
Let’s say we want to write a test for a basic bank account that has a balance that can be incremented:
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)
}
}
}