Behavior-Driven Development - BDD

Behavior-Driven Development (BDD) is an agile development technique, that focuses on the engagement between developers and non-technical people such as product owners from the business. The idea is pretty simple: use the same language as the business uses in order to extract the reason why the code you are building exists in the first place. BDD ends up minimizing the translation between tech language and business language, creating more synergy and less noise between information technology and business.

BDD tests describe what the application needs to do, and how it behaves. It's very common to write down these tests using pair programing between business people and developers. ScalaTest is a BDD framework. Play framework has a great integration with ScalaTest. Let's get started with ScalaTest and Play right now.

MyFirstPlaySpec.scala - First BDD with ScalaTest and the Play framework

The MyFirstPlaySpec.scala class should contain the following code:

class MyFirstPlaySpec extends PlaySpec {

"x + 1 " must {

"be 2 if x=1 " in { val sum = 1 + 1 sum mustBe 2


"be 0 if x=-1 " in { val sum = -1 + 1 sum mustBe 0




So, you create a class called MyFirstPlaySpec, and we extend it from PlaySpec in order to get Play framework ScalaTest support. Then we create two functions to test the sum of two numbers. In the first test, 1 +1 should be 2, and in the second, -1 + 1 should be 0. When we execute mustBe, it is the same thing as doing an assert in Junit. The main difference here is that the test has behavior explicitly on the Spec. Now we can run the test by typing the following:

$ activator "test-only MyFirstPlaySpec"

You will see the following result:

< Prev   CONTENTS   Source   Next >