ScalaTest 1.0

This document is the API specification for ScalaTest 1.0

Class Summary
trait AbstractSuite extends AnyRef
Trait that defines abstract methods that are implemented in Suite that can be overriden in stackable modification traits.
trait Assertions extends AnyRef
Trait that contains ScalaTest's basic assertion methods.
trait BeforeAndAfter extends BeforeAndAfterEach with BeforeAndAfterAll
This trait has been deprecated and will be removed in a future version of ScalaTest. If you are only using its beforeEach and/or afterEach methods, mix in BeforeAndAfterEach instead. If you are only using its beforeAll and/or afterAll methods, mix in BeforeAndAfterAll instead. If you are using at least one "each" and one "all" method, mix in BeforeAndAfterEach with BeforeAndAfterAll instead.
trait BeforeAndAfterAll extends AbstractSuite with AnyRef
Trait that can be mixed into suites that need methods invoked before and after executing the suite. This trait allows code to be executed before and/or after all the tests and nested suites of a suite are run. This trait overrides run (the main run method that takes seven parameters, an optional test name, reporter, stopper, filter, configMap, optional distributor, and tracker) and calls the beforeAll method, then calls super.run. After the super.run invocation completes, whether it returns normally or completes abruptly with an exception, this trait's run method will invoke afterAll.
trait BeforeAndAfterEach extends AbstractSuite with AnyRef
Trait that can be mixed into suites that need methods invoked before and after running each test. This trait facilitates a style of testing in which mutable fixture objects held in instance variables are replaced or reinitialized before each test or suite. Here's an example:
 import org.scalatest._
 import scala.collection.mutable.ListBuffer

 class MySuite extends BeforeAndAfterEach {

   // Fixtures as reassignable variables and mutable objects
   var sb: StringBuilder = _
   val lb = new ListBuffer[String]

   override def beforeEach() {
     sb = new StringBuilder("ScalaTest is ")
     lb.clear()
   }

   def testEasy() {
     sb.append("easy!")
     assert(sb.toString === "ScalaTest is easy!")
     assert(lb.isEmpty)
     lb += "sweet"
   }

   def testFun() {
     sb.append("fun!")
     assert(sb.toString === "ScalaTest is fun!")
     assert(lb.isEmpty)
   }
 }
 
trait Distributor extends (Suite, Tracker) => Unit
Trait whose instances facilitate parallel execution of Suites. An optional Distributor is passed to the run method of Suite. If a Distributor is indeed passed, trait Suite's implementation of run will populate that Distributor with its nested Suites (by passing them to the Distributor's apply method) rather than executing the nested Suites directly. It is then up to another thread or process to execute those Suites.
class DuplicateTestNameException (testName : java.lang.String, failedCodeStackDepth : Int) extends StackDepthException
Exception that indicates an attempt was made to register a test that had the same name as a test already registered in the same suite. The purpose of this exception is to encapsulate information about the stack depth at which the line of code that made this attempt resides, so that information can be presented to the user that makes it quick to find the problem line of code. (In other words, the user need not scan through the stack trace to find the correct filename and line number of the offending code.)
trait FeatureSpec extends Suite
A suite of tests in which each test represents one scenario of a feature. FeatureSpec is intended for writing tests that are "higher level" than unit tests, for example, integration tests, functional tests, and acceptance tests. You can use FeatureSpec for unit testing if you prefer, however. Here's an example:
 import org.scalatest.FeatureSpec
 import org.scalatest.GivenWhenThen
 import scala.collection.mutable.Stack
 
 class StackFeatureSpec extends FeatureSpec with GivenWhenThen {
 
   feature("The user can pop an element off the top of the stack") {
 
     info("As a programmer")
     info("I want to be able to pop items off the stack")
     info("So that I can get them in last-in-first-out order")
 
     scenario("pop is invoked on a non-empty stack") {
 
       given("a non-empty stack")
       val stack = new Stack[Int]
       stack.push(1)
       stack.push(2)
       val oldSize = stack.size
 
       when("when pop is invoked on the stack")
       val result = stack.pop()
 
       then("the most recently pushed element should be returned")
       assert(result === 2)
 
       and("the stack should have one less item than before")
       assert(stack.size === oldSize - 1)
     }
 
     scenario("pop is invoked on an empty stack") {
 
       given("an empty stack")
       val emptyStack = new Stack[String]
 
       when("when pop is invoked on the stack")
       then("NoSuchElementException should be thrown")
       intercept[NoSuchElementException] {
         emptyStack.pop()
       }
 
       and("the stack should still be empty")
       assert(emptyStack.isEmpty)
     }
   }
 }
 
final class Filter (val tagsToInclude : scala.Option[scala.collection.immutable.Set[java.lang.String]], val tagsToExclude : scala.collection.immutable.Set[java.lang.String]) extends (scala.collection.immutable.Set[java.lang.String], scala.collection.immutable.Map[java.lang.String, scala.collection.immutable.Set[java.lang.String]]) => scala.List[(java.lang.String, Boolean)]
Filter whose apply method determines which of the passed tests to run and ignore based on tags to include and exclude passed as as class parameters.
trait FlatSpec extends Suite with ShouldVerb with MustVerb with CanVerb
Trait that facilitates a “behavior-driven” style of development (BDD), in which tests are combined with text that specifies the behavior the tests verify. (In BDD, the word example is usually used instead of test. The word test will not appear in your code if you use FlatSpec, so if you prefer the word example you can use it. However, in this documentation the word test will be used, for clarity and to be consistent with the rest of ScalaTest.) Trait FlatSpec is so named because your specification text and tests line up flat against the left-side indentation level, with no nesting needed.

trait FunSuite extends Suite
A suite of tests in which each test is represented as a function value. The “Fun” in FunSuite stands for “function.” Here's an example FunSuite:
 import org.scalatest.FunSuite

 class MySuite extends FunSuite {

   test("addition") {
     val sum = 1 + 1
     assert(sum === 2)
     assert(sum + 2 === 4)
   }

   test("subtraction") {
     val diff = 4 - 1
     assert(diff === 3)
     assert(diff - 2 === 1)
   }
 }
 
trait GivenWhenThen extends AnyRef
Trait that contains methods named given, when, then, and and, which take a string message and implicit Informer, and forward the message to the informer.
abstract class Group (name : java.lang.String) extends Tag
Group has been deprecated. It will be removed in a future release of ScalaTest. Please change any Group subclasses you have created so that they extend class Tag directly instead.
trait Informer extends AnyRef
Trait to which custom information about a running suite of tests can be reported.
class NotAllowedException (message : java.lang.String, failedCodeStackDepth : Int) extends StackDepthException
Exception that indicates something was attempted in test code that is not allowed. For example, in a FeatureSpec, it is not allowed to nest a feature clause inside another feature clause. If this is attempted, the construction of that suite will fail with a NotAllowedException.
trait OneInstancePerTest extends AbstractSuite with AnyRef
Trait that facilitates a style of testing in which each test is run in its own instance of the suite class to isolate each test from the side effects of the other tests in the suite.
trait ParallelTestExecution extends OneInstancePerTest
Trait that causes that the tests of any suite it is mixed into to be run in parallel if a Distributor is passed to runTests.
final class PendingNothing extends AnyRef
Type that is used as the return type of the pending method in class Suite, which always completes abruptly with a TestPendingException.
trait PrivateMethodTester extends AnyRef
Trait that facilitates the testing of private methods. To test a private method, mix in trait PrivateMethodTester and create a PrivateMethod object, like this:
 val decorateToStringValue = PrivateMethod[String]('decorateToStringValue)
 
class Report (val name : java.lang.String, val message : java.lang.String, val throwable : scala.Option[java.lang.Throwable], val rerunnable : scala.Option[Rerunnable], val threadName : java.lang.String, val date : java.util.Date) extends AnyRef
trait Reporter extends (Event) => Unit
Trait whose instances collect the results of a running suite of tests and presents those results in some way to the user. Instances of this trait can be called "report functions" or "reporters."
trait Rerunnable extends AnyRef
Trait formerly used to rerun tests or other entities (such as suites). Note: this trait has been deprecated and will be removed in a future version of ScalaTest.
trait Rerunner extends (Reporter, Stopper, Filter, scala.collection.immutable.Map[java.lang.String, Any], scala.Option[Distributor], Tracker, java.lang.ClassLoader) => Unit
Trait whose instances can rerun tests or other entities (such as suites). An object extending this trait can be passed to a Reporter as part of a Report. The test or other entity about which the report is made can then be rerun by invoking the rerun method on the Rerunnable.
trait ResourcefulReporter extends Reporter
Subtrait of Reporter that contains a dispose method for releasing any finite, non-memory resources, such as file handles, held by the Reporter. Runner will invoke dispose on any ResourcefulReporter when it no longer needs the Reporter.
trait SequentialNestedSuiteExecution extends AbstractSuite with AnyRef
Trait that causes that the nested suites of any suite it is mixed into to be run sequentially even if a Distributor is passed to runNestedSuites. This trait overrides the runNestedSuites method and fowards every parameter passed to it to a superclass invocation of runNestedSuites, except it always passes None for the Distributor. Mix in this trait into any suite whose nested suites need to be run sequentially even with the rest of the run is being executed concurrently.
trait Spec extends Suite
Trait that facilitates a “behavior-driven” style of development (BDD), in which tests are combined with text that specifies the behavior the tests verify. (Note: In BDD, the word example is usually used instead of test. The word test will not appear in your code if you use WordSpec, so if you prefer the word example you can use it. However, in this documentation the word test will be used, for clarity and to be consistent with the rest of ScalaTest.) Here's an example Spec:
 import org.scalatest.Spec
 import scala.collection.mutable.Stack

 class StackSpec extends Spec {

   describe("A Stack") {

     it("should pop values in last-in-first-out order") {
       val stack = new Stack[Int]
       stack.push(1)
       stack.push(2)
       assert(stack.pop() === 2)
       assert(stack.pop() === 1)
     }

     it("should throw NoSuchElementException if an empty stack is popped") {
       val emptyStack = new Stack[String]
       intercept[NoSuchElementException] {
         emptyStack.pop()
       }
     }
   }
 }
 
class SpecReport (val override name : java.lang.String, val override message : java.lang.String, val plainSpecText : java.lang.String, val formattedSpecText : java.lang.String, val includeInSpecOutput : Boolean, val override throwable : scala.Option[java.lang.Throwable], val override rerunnable : scala.Option[Rerunnable], val override threadName : java.lang.String, val override date : java.util.Date) extends Report
trait StackDepth extends AnyRef
Trait that encapsulates the information required of an exception thrown by ScalaTest's assertions and matchers, which includes a stack depth at which the failing line of test code resides.
abstract class StackDepthException (val message : scala.Option[java.lang.String], val cause : scala.Option[java.lang.Throwable], val failedCodeStackDepth : Int) extends java.lang.RuntimeException with StackDepth
Exception class that encapsulates information about the stack depth at which the line of code that failed resides, so that information can be presented to the user that makes it quick to find the failing line of code. (In other words, the user need not scan through the stack trace to find the correct filename and line number of the problem code.) Having a stack depth is more useful in a testing environment in which test failures are implemented as thrown exceptions, as is the case in ScalaTest's built-in suite traits.
trait Stopper extends () => Boolean
Trait whose instances can indicate whether a stop has been requested. This is passed in to the run method of Suite, so that running suites of tests can be requested to stop early.
trait Suite extends Assertions with AbstractSuite
A suite of tests. A Suite instance encapsulates a conceptual suite (i.e., a collection) of tests.
class SuperSuite (val override nestedSuites : scala.List[Suite]) extends Suite
A Suite class that takes a List[Suite] parameter, which overrides the nestedSuites method of trait Suite.
abstract class Tag (val name : java.lang.String) extends AnyRef
Abstract class whose subclasses can be used to tag tests in types FunSuite, Spec, FlatSpec, WordSpec, FeatureSpec, and their sister traits in the org.scalatest.fixture package. For example, if you define:
 object SlowTest extends Tag("SlowTest")
 
then you can tag a test as a SlowTest in a FunSuite or FixtureFunSuite like this:
 import org.scalatest.FunSuite

 class MySuite extends FunSuite {

   test("my test", SlowTest) {
     Thread.sleep(1000)
   }
 }
 
class TestFailedException (message : scala.Option[java.lang.String], cause : scala.Option[java.lang.Throwable], failedCodeStackDepth : Int) extends StackDepthException
Exception that indicates a test failed. The purpose of this exception is to encapsulate information about the stack depth at which the line of test code that failed resides, so that information can be presented to the user that makes it quick to find the failing line of test code. (In other words, the user need not scan through the stack trace to find the correct filename and line number of the failing test.)
class TestPendingException extends java.lang.RuntimeException with AnyRef
Exception thrown to indicate a test is pending.
class TestRegistrationClosedException (message : java.lang.String, failedCodeStackDepth : Int) extends StackDepthException
Exception that indicates an action that is only allowed during a suite's test registration phase, such as registering a test to run or ignore, was attempted after registration had already closed.
final class Tracker (firstOrdinal : Ordinal) extends AnyRef
Class that tracks the progress of a series of Ordinals produced by invoking next and nextNewOldPair on the current Ordinal.
trait WordSpec extends Suite with ShouldVerb with MustVerb with CanVerb
Trait that facilitates a “behavior-driven” style of development (BDD), in which tests are combined with text that specifies the behavior the tests verify. (In BDD, the word example is usually used instead of test. The word test will not appear in your code if you use WordSpec, so if you prefer the word example you can use it. However, in this documentation the word test will be used, for clarity and to be consistent with the rest of ScalaTest.) Trait WordSpec is so named because you specification text is structured by placing words after strings. Here's an example WordSpec:
 import org.scalatest.WordSpec
 import scala.collection.mutable.Stack

 class StackSpec extends WordSpec {

   "A Stack" should {

     "pop values in last-in-first-out order" in {
       val stack = new Stack[Int]
       stack.push(1)
       stack.push(2)
       assert(stack.pop() === 2)
       assert(stack.pop() === 1)
     }

     "throw NoSuchElementException if an empty stack is popped" in {
       val emptyStack = new Stack[String]
       intercept[NoSuchElementException] {
         emptyStack.pop()
       }
     }
   }
 }
 
Object Summary
object Assertions extends Assertions
Companion object that facilitates the importing of Assertions members as an alternative to mixing it in. One use case is to import Assertions members so you can use them in the Scala interpreter:
 $scala -classpath scalatest.jar
 Welcome to Scala version 2.7.3.final (Java HotSpot(TM) Client VM, Java 1.5.0_16).
 Type in expressions to have them evaluated.
 Type :help for more information.
 
 scala> import org.scalatest.Assertions._
 import org.scalatest.Assertions._
 
 scala> assert(1 === 2)
 org.scalatest.TestFailedException: 1 did not equal 2
 	at org.scalatest.Assertions$class.assert(Assertions.scala:211)
 	at org.scalatest.Assertions$.assert(Assertions.scala:511)
 	at .(:7)
 	at .()
 	at RequestResult$.(:3)
 	at RequestResult$.()
 	at RequestResult$result()
 	at sun.reflect.NativeMethodAccessorImpl.invoke...

 scala> expect(3) { 1 + 3 }
 org.scalatest.TestFailedException: Expected 3, but got 4
 	at org.scalatest.Assertions$class.expect(Assertions.scala:447)
 	at org.scalatest.Assertions$.expect(Assertions.scala:511)
 	at .(:7)
 	at .()
 	at RequestResult$.(:3)
 	at RequestResult$.()
 	at RequestResult$result()
 	at sun.reflect.NativeMethodAccessorImpl.in...

 scala> val caught = intercept[StringIndexOutOfBoundsException] { "hi".charAt(-1) }
 caught: StringIndexOutOfBoundsException = java.lang.StringIndexOutOfBoundsException: String index out of range: -1
 
object Filter extends AnyRef
object GivenWhenThen extends GivenWhenThen
Companion object that facilitates the importing of GivenWhenThen members as an alternative to mixing it in.
object PrivateMethodTester extends PrivateMethodTester
Companion object that facilitates the importing of PrivateMethodTester members as an alternative to mixing it in. One use case is to import PrivateMethodTester members so you can use them in the Scala interpreter:
 $scala -classpath scalatest.jar
 Welcome to Scala version 2.7.5.final (Java HotSpot(TM) Client VM, Java 1.5.0_16).
 Type in expressions to have them evaluated.
 Type :help for more information.
 
 scala> import org.scalatest.PrivateMethodTester._                 
 import org.scalatest.PrivateMethodTester._
 
 scala> class Example {
      |   private def addSesame(prefix: String) = prefix + " sesame"
      | }
 defined class Example
 
 scala> val example = new Example
 example: Example = Example@d8b6fe
 
 scala> val addSesame = PrivateMethod[String]('addSesame)           
 addSesame: org.scalatest.PrivateMethodTester.PrivateMethod[String] = org.scalatest.PrivateMethodTester$PrivateMethod@5cdf95
 
 scala> example invokePrivate addSesame("open")                     
 res0: String = open sesame