org.scalatest.fixture

trait FixtureSuite

[source: org/scalatest/fixture/FixtureSuite.scala]

trait FixtureSuite
extends Suite
Suite that can pass a fixture object into its tests.

This trait behaves similarly to trait org.scalatest.Suite, except that tests may have a fixture parameter. The type of the fixture parameter is defined by the abstract FixtureParam type, which is declared as a member of this trait. This trait also declares an abstract withFixture method. This withFixture method takes a OneArgTest, which is a nested trait defined as a member of this trait. OneArgTest has an apply method that takes a FixtureParam. This apply method is responsible for running a test. This trait's runTest method delegates the actual running of each test to withFixture, passing in the test code to run via the OneArgTest argument. The withFixture method (abstract in this trait) is responsible for creating the fixture argument and passing it to the test function.

Subclasses of this trait must, therefore, do three things differently from a plain old org.scalatest.Suite:

  1. define the type of the fixture parameter by specifying type FixtureParam
  2. define the withFixture(OneArgTest) method
  3. write test methods that take a fixture parameter (You can also define test methods that don't take a fixture parameter.)

Here's an example:

 import org.scalatest.fixture.FixtureSuite
 import java.io.FileReader
 import java.io.FileWriter
 import java.io.File
 
 class MySuite extends FixtureSuite {

   // 1. define type FixtureParam
   type FixtureParam = FileReader

   // 2. define the withFixture method
   def withFixture(test: OneArgTest) {

     val FileName = "TempFile.txt"

     // Set up the temp file needed by the test
     val writer = new FileWriter(FileName)
     try {
       writer.write("Hello, test!")
     }
     finally {
       writer.close()
     }

     // Create the reader needed by the test
     val reader = new FileReader(FileName)
  
     try {
       // Run the test using the temp file
       test(reader)
     }
     finally {
       // Close and delete the temp file
       reader.close()
       val file = new File(FileName)
       file.delete()
     }
   }
 
   // 3. write test methods that take a fixture parameter
   def testReadingFromTheTempFile(reader: FileReader) {
     var builder = new StringBuilder
     var c = reader.read()
     while (c != -1) {
       builder.append(c.toChar)
       c = reader.read()
     }
     assert(builder.toString === "Hello, test!")
   }
 
   def testFirstCharOfTheTempFile(reader: FileReader) {
     assert(reader.read() === 'H')
   }
 
   // (You can also write tests methods that don't take a fixture parameter.)
   def testWithoutAFixture() { 
     without fixture {
       assert(1 + 1 === 2)
     }
   }
 }
 

If the fixture you want to pass into your tests consists of multiple objects, you will need to combine them into one object to use this trait. One good approach to passing multiple fixture objects is to encapsulate them in a tuple. Here's an example that takes the tuple approach:

 import org.scalatest.fixture.FixtureSuite
 import scala.collection.mutable.ListBuffer

 class MySuite extends FixtureSuite {

   type FixtureParam = (StringBuilder, ListBuffer[String])

   def withFixture(test: OneArgTest) {

     // Create needed mutable objects
     val stringBuilder = new StringBuilder("ScalaTest is ")
     val listBuffer = new ListBuffer[String]

     // Invoke the test function, passing in the mutable objects
     test(stringBuilder, listBuffer)
   }

   def testEasy(fixture: Fixture) {
     val (builder, buffer) = fixture
     builder.append("easy!")
     assert(builder.toString === "ScalaTest is easy!")
     assert(buffer.isEmpty)
     buffer += "sweet"
   }

   def testFun(fixture: Fixture) {
     val (builder, buffer) = fixture
     builder.append("fun!")
     assert(builder.toString === "ScalaTest is fun!")
     assert(buffer.isEmpty)
   }
 }
 

When using a tuple to pass multiple fixture objects, it is usually helpful to give names to each individual object in the tuple with a pattern-match assignment, as is done at the beginning of each test method here with:

 val (builder, buffer) = fixture
 

Another good approach to passing multiple fixture objects is to encapsulate them in a case class. Here's an example that takes the case class approach:

 import org.scalatest.fixture.FixtureSuite
 import scala.collection.mutable.ListBuffer

 class MySuite extends FixtureSuite {

   case class FixtureHolder(builder: StringBuilder, buffer: ListBuffer[String])

   type FixtureParam = FixtureHolder

   def withFixture(test: OneArgTest) {

     // Create needed mutable objects
     val stringBuilder = new StringBuilder("ScalaTest is ")
     val listBuffer = new ListBuffer[String]

     // Invoke the test function, passing in the mutable objects
     test(FixtureHolder(stringBuilder, listBuffer))
   }

   def testEasy(fixture: Fixture) {
     import fixture._
     builder.append("easy!")
     assert(builder.toString === "ScalaTest is easy!")
     assert(buffer.isEmpty)
     buffer += "sweet"
   }

   def testFun(fixture: Fixture) {
     fixture.builder.append("fun!")
     assert(fixture.builder.toString === "ScalaTest is fun!")
     assert(fixture.buffer.isEmpty)
   }
 }
 

When using a case class to pass multiple fixture objects, it can be helpful to make the names of each individual object available as a single identifier with an import statement. This is the approach taken by the testEasy method in the previous example. Because it imports the members of the fixture object, the test method code can just use them as unqualified identifiers:

 def testEasy(fixture: Fixture) {
   import fixture._
   builder.append("easy!")
   assert(builder.toString === "ScalaTest is easy!")
   assert(buffer.isEmpty)
   buffer += "sweet"
 }
 

Alternatively, you may sometimes prefer to qualify each use of a fixture object with the name of the fixture parameter. This approach, taken by the testFun method in the previous example, makes it more obvious which variables in your test method are part of the passed-in fixture:

 def testFun(fixture: Fixture) {
   fixture.builder.append("fun!")
   assert(fixture.builder.toString === "ScalaTest is fun!")
   assert(fixture.buffer.isEmpty)
 }
 

Configuring fixtures and tests

Sometimes you may want to write tests that are configurable. For example, you may want to write a suite of tests that each take an open temp file as a fixture, but whose file name is specified externally so that the file name can be can be changed from run to run. To accomplish this the OneArgTest trait has a configMap method, which will return a Map[String, Any] from which configuration information may be obtained. The runTest method of this trait will pass a OneArgTest to withFixture whose configMap method returns the configMap passed to runTest. Here's an example in which the name of a temp file is taken from the passed configMap:

 import org.scalatest.fixture.FixtureSuite
 import java.io.FileReader
 import java.io.FileWriter
 import java.io.File
 
 class MySuite extends FixtureSuite {

   type FixtureParam = FileReader

   def withFixture(test: OneArgTest) {

     require(
       test.configMap.contains("TempFileName"),
       "This suite requires a TempFileName to be passed in the configMap"
     )

     // Grab the file name from the configMap
     val FileName = test.configMap("TempFileName")

     // Set up the temp file needed by the test
     val writer = new FileWriter(FileName)
     try {
       writer.write("Hello, test!")
     }
     finally {
       writer.close()
     }

     // Create the reader needed by the test
     val reader = new FileReader(FileName)
  
     try {
       // Run the test using the temp file
       test(reader)
     }
     finally {
       // Close and delete the temp file
       reader.close()
       val file = new File(FileName)
       file.delete()
     }
   }
 
   def testReadingFromTheTempFile(reader: FileReader) {
     var builder = new StringBuilder
     var c = reader.read()
     while (c != -1) {
       builder.append(c.toChar)
       c = reader.read()
     }
     assert(builder.toString === "Hello, test!")
   }
 
   def testFirstCharOfTheTempFile(reader: FileReader) {
     assert(reader.read() === 'H')
   }
 }
 

If you want to pass into each test the entire configMap that was passed to runTest, you can mix in trait ConfigMapFixture. See the documentation for ConfigMapFixture for the details, but here's a quick example of how it looks:

  import org.scalatest.fixture.FixtureSuite
  import org.scalatest.fixture.ConfigMapFixture

  class MySuite extends FixtureSuite with ConfigMapFixture {

    def testHello(configMap: Map[String, Any]) {
      // Use the configMap passed to runTest in the test
      assert(configMap.contains("hello")
    }

    def testWorld(configMap: Map[String, Any]) {
      assert(configMap.contains("world")
    }
  }
 

Note: because a FixtureSuite's test methods are invoked with reflection at runtime, there is no good way to create a FixtureSuite containing test methods that take different fixtures. If you find you need to do this, you may want to split your class into multiple FixtureSuites, each of which contains test methods that take the common Fixture type defined in that class, or use a MultipleFixtureFunSuite.

Author
Bill Venners
Direct Known Subclasses:
FixtureFeatureSpec, FixtureFlatSpec, FixtureFunSuite, FixtureSpec, FixtureWordSpec

Type Summary
protected abstract type FixtureParam
The type of the fixture parameter that can be passed into tests in this suite.
Method Summary
protected override def runTest (testName : java.lang.String, reporter : Reporter, stopper : Stopper, configMap : scala.collection.immutable.Map[java.lang.String, Any], tracker : Tracker) : Unit
Run a test.
override def tags : scala.collection.immutable.Map[java.lang.String, scala.collection.immutable.Set[java.lang.String]]
A Map whose keys are String tag names with which tests in this Suite are marked, and whose values are the Set of test names marked with each tag. If this Suite contains no tags, this method returns an empty Map.
override def testNames : scala.collection.immutable.Set[java.lang.String]
An Set of test names. If this Suite contains no tests, this method returns an empty Set.
protected abstract def withFixture (test : OneArgTest) : Unit
Run the passed test function with a fixture created by this method.
Methods inherited from Suite
nestedSuites, execute, execute, execute, execute, groups, withFixture, runTests, run, runNestedSuites, suiteName, pending, pendingUntilFixed, expectedTestCount
Methods inherited from Assertions
assert, assert, assert, assert, convertToEqualizer, intercept, expect, expect, fail, fail, fail, fail
Methods inherited from AnyRef
getClass, hashCode, equals, clone, toString, notify, notifyAll, wait, wait, wait, finalize, ==, !=, eq, ne, synchronized
Methods inherited from Any
==, !=, isInstanceOf, asInstanceOf
Class Summary
protected trait OneArgTest extends (FixtureParam) => Unit
Trait whose instances encapsulate a test function that takes a fixture and config map.
Type Details
protected abstract type FixtureParam
The type of the fixture parameter that can be passed into tests in this suite.

Method Details
protected abstract def withFixture(test : OneArgTest) : Unit
Run the passed test function with a fixture created by this method.

This method should create the fixture object needed by the tests of the current suite, invoke the test function (passing in the fixture object), and if needed, perform any clean up needed after the test completes. For more detail and examples, see the main documentation for this trait.

Parameters
fun - the OneArgTest to invoke, passing in a fixture

override def tags : scala.collection.immutable.Map[java.lang.String, scala.collection.immutable.Set[java.lang.String]]
A Map whose keys are String tag names with which tests in this Suite are marked, and whose values are the Set of test names marked with each tag. If this Suite contains no tags, this method returns an empty Map.

This trait's implementation of this method uses Java reflection to discover any Java annotations attached to its test methods. The fully qualified name of each unique annotation that extends TagAnnotation is considered a tag. This trait's implementation of this method, therefore, places one key/value pair into to the Map for each unique tag annotation name discovered through reflection. The mapped value for each tag name key will contain the test method name, as provided via the testNames method.

Subclasses may override this method to define and/or discover tags in a custom manner, but overriding method implementations should never return an empty Set as a value. If a tag has no tests, its name should not appear as a key in the returned Map.

Note, the TagAnnotation annotation was introduced in ScalaTest 1.0, when "groups" were renamed to "tags." In 1.0 and 1.1, the TagAnnotation will continue to not be required by an annotation on a Suite method. Any annotation on a Suite method will be considered a tag until 1.2, to give users time to add TagAnnotations on any tag annotations they made prior to the 1.0 release. From 1.2 onward, only annotations themselves annotated by TagAnnotation will be considered tag annotations.

Overrides
Suite.tags

override def testNames : scala.collection.immutable.Set[java.lang.String]
An Set of test names. If this Suite contains no tests, this method returns an empty Set.

This trait's implementation of this method uses Java reflection to discover all public methods whose name starts with "test", which take either nothing or a single Informer as parameters. For each discovered test method, it assigns a test name comprised of just the method name if the method takes no parameters, or the method name plus (Informer) if the method takes a Informer. Here are a few method signatures and the names that this trait's implementation assigns them:

  def testCat() {}         // test name: "testCat"
  def testCat(Informer) {} // test name: "testCat(Informer)"
  def testDog() {}         // test name: "testDog"
  def testDog(Informer) {} // test name: "testDog(Informer)"
  def test() {}            // test name: "test"
  def test(Informer) {}    // test name: "test(Informer)"
  

This trait's implementation of this method returns an immutable Set of all such names, excluding the name testNames. The iterator obtained by invoking elements on this returned Set will produce the test names in their natural order, as determined by String's compareTo method.

This trait's implementation of runTests invokes this method and calls runTest for each test name in the order they appear in the returned Set's iterator. Although this trait's implementation of this method returns a Set whose iterator produces String test names in a well-defined order, the contract of this method does not required a defined order. Subclasses are free to override this method and return test names in an undefined order, or in a defined order that's different from String's natural order.

Subclasses may override this method to produce test names in a custom manner. One potential reason to override testNames is to run tests in a different order, for example, to ensure that tests that depend on other tests are run after those other tests. Another potential reason to override is allow tests to be defined in a different manner, such as methods annotated @Test annotations (as is done in JUnitSuite and TestNGSuite) or test functions registered during construction (as is done in FunSuite and Spec).

Overrides
Suite.testNames

protected override def runTest(testName : java.lang.String, reporter : Reporter, stopper : Stopper, configMap : scala.collection.immutable.Map[java.lang.String, Any], tracker : Tracker) : Unit
Run a test.

This trait's implementation uses Java reflection to invoke on this object the test method identified by the passed testName.

Implementations of this method are responsible for ensuring a TestStarting event is fired to the Reporter before executing any test, and either TestSucceeded, TestFailed, or TestPending after executing any nested Suite. (If a test is marked with the org.scalatest.Ignore tag, the runTests method is responsible for ensuring a TestIgnored event is fired and that this runTest method is not invoked for that ignored test.)

Parameters
testName - the name of one test to run.
reporter - the Reporter to which results will be reported
stopper - the Stopper that will be consulted to determine whether to stop execution early.
configMap - a Map of key-value pairs that can be used by the executing Suite of tests.
tracker - a Tracker tracking Ordinals being fired by the current thread.
Throws
NullPointerException - if any of testName, reporter, stopper, configMap or tracker is null.
IllegalArgumentException - if testName is defined, but no test with the specified test name exists in this Suite
Overrides
Suite.runTest


Copyright (C) 2001-2010 Artima, Inc. All rights reserved.