ScalaTest 101: How to install ScalaTest

Problem: You want to begin using ScalaTest to write TDD- or BDD-style unit tests for your Scala applications.

Solution

The easiest way to use Scala and ScalaTest in production projects is to use the Simple Build Tool (SBT) to manage your project, so the recipes in this chapter assume you’ll be using SBT. (See Chapter 18 of the Scala Cookbook for tools that let you easily create an SBT directory structure, as well as GitHub projects you can clone to quickly begin working with ScalaTest and other tools.)

To use ScalaTest with SBT 0.10 or newer with Scala 2.10.0, just add a line like this to your build.sbt file:

// valid for Scala 2.10.0 and SBT 0.10
libraryDependencies += "org.scalatest" %% "scalatest" % "1.9.1" % "test"

If you’re more comfortable using JAR files, download the latest file from the ScalaTest download page.

Discussion

This recipe is intentionally short and simple, because your next step is to decide whether you want to use a TDD or BDD style of testing.

When deciding whether you want to write tests in a TDD or BDD style, it’s important to know that ScalaTest provides classes to support a number of testing “styles.” For instance, a FunSuite is meant to feel comfortable for developers coming to ScalaTest from JUnit/NUnit. It’s used in the TDD-style tests in this chapter.

A FlatSpec offers “a nice first step for teams wanting to move from JUnit to a BDD style,” whereas FunSpec is for teams coming from the Ruby RSpec tool. FunSpec is used in the BDD examples in this chapter.

Beyond these basic styles, there are still more. From the ScalaTest documentation:

  • WordSpec is meant “for teams coming from specs or specs2.”
  • FreeSpec “gives absolute freedom on how specification text should be written.”
  • PropSpec is “for teams that want to write tests exclusively in terms of property checks.”
  • FeatureSpec “is primarily intended for acceptance testing, including facilitating the process of programmers working alongside non-programmers to define the acceptance requirements.”

See the “Selecting a ScalaTest testing style” link in the See Also section for more details on choosing a style.

See Also

See the following resources for more information:

  • For information on SBT, see the recipes in Chapter 18 of the Scala Cookbook
  • Selecting a ScalaTest testing style: http://www.scalatest.org/userguide/selectinga_style
  • My “Basic SBT Project with ScalaTest” project on GitHub: https://github.com/alvinj/BasicScalaSbtProjectWithScalatest
  • ScalaTest download page: http://www.scalatest.org/download
  • The specs2 testing library: http://etorreborre.github.io/specs2/