ScalaTest quick start

To get started with ScalaTest, copy this FlatSpec into a file named ExampleSpec.scala:

import collection.mutable.Stack
import org.scalatest._

class ExampleSpec extends FlatSpec with Matchers {

    val stack = new Stack[Int]
    stack.pop() should be (2)
    stack.pop() should be (1)

    val emptyStack = new Stack[Int]
    a [NoSuchElementException] should be thrownBy {

In a FlatSpec, you combine tests with text that specifies the behavior being tested. Each test name specifies a bit of behavior about a subject under test. You start by identifying the subject with a string name (here, "A Stack"), write should, then write another string that describes the behavior expected of the subject. The code of the test appears in curly braces after an in following the text.

You can compile this FlatSpec like this (using this Jar file):

$ scalac -cp scalatest_2.11-2.2.4.jar ExampleSpec.scala

Here's how you run it:

$ scala -cp scalatest_2.11-2.2.4.jar ExampleSpec
Discovery starting.
Discovery completed in 21 milliseconds.
Run starting. Expected test count is: 2
A Stack
- should throw NoSuchElementException if an empty stack is popped
Run completed in 76 milliseconds.
Total number of tests run: 2
Suites: completed 1, aborted 0
All tests passed.

To get going on a project, first select a style for unit testing. If you don't have a preference, we recommend starting with FlatSpec for unit testing. We think FlatSpec is a good default choice because it has a flat structure, similar to the XUnit-style tests familiar to most users, but encourages a BDD-style of using descriptive specifications of behavior for test names.

(For a quick guide to ScalaTest's style traits, see the Style trait use cases table in the user guide.)

Once you've selected your unit testing style, create an abstract base class (not a trait) for your unit tests. You should mix into this class all the traits you think you'll use a lot. You can use any name, but we recommend the name UnitSpec. Here's an example:

package com.mycompany.myproject

import org.scalatest._

abstract class UnitSpec extends FlatSpec with Matchers with
  OptionValues with Inside with Inspectors

You can now write unit tests for your project using your custom base class:

package com.mycompany.myproject

import org.scalatest._

class MySpec extends UnitSpec {
  // Your tests here

To include ScalaTest in your sbt project, simply add this line:


To include ScalaTest in your Maven project, use:


You are off and running! For more information, consult the user guide.









