package fixture
Type Members
-    trait AsyncConfigMapFixture extends AnyRefTrait that when mixed into a fixture.AsyncTestSuitepasses the config map passed torunTestas a fixture into each test.Trait that when mixed into a fixture.AsyncTestSuitepasses the config map passed torunTestas a fixture into each test.Here's an example in which tests just check to make sure "hello"and"world"are defined keys in the config map:package org.scalatest.examples.fixture.configmapfixture 
 import org.scalatest._
 class ExampleAsyncSpec extends fixture.AsyncFlatSpec with fixture.AsyncConfigMapFixture with Matchers {
 "The config map" should "contain hello" in { configMap => // Use the configMap passed to runTest in the test configMap should contain key "hello" }
 it should "contain world" in { configMap => configMap should contain key "world" } }If you run this class without defining "hello"and"world"in the confg map, the tests will fail:scala> org.scalatest.run(new ExampleSpec) ExampleSpec: The config map - should contain hello *** FAILED *** Map() did not contain key "hello" ( :20) - should contain world *** FAILED *** Map() did not contain key "world" ( :24) If you do define "hello"and"world"keys in the confg map, the tests will success:scala> org.scalatest.run(new ExampleSpec, configMap = Map("hello" -> "hi", "world" -> "globe")) ExampleSpec: The config map - should contain hello - should contain world
-   abstract  class AsyncFeatureSpec extends AsyncFeatureSpecLikeA sister class to org.scalatest.AsyncFeatureSpecthat can pass a fixture object into its tests.A sister class to org.scalatest.AsyncFeatureSpecthat can pass a fixture object into its tests.Recommended Usage: Use class fixture.AsyncFeatureSpecin situations for whichAsyncFeatureSpecwould be a good choice, when all or most tests need the same fixture objects that must be cleaned up afterwards. Note:fixture.AsyncFeatureSpecis intended for use in special situations, with classAsyncFeatureSpecused for general needs. For more insight into wherefixture.AsyncFeatureSpecfits in the big picture, see thewithFixture(OneArgAsyncTest)subsection of the Shared fixtures section in the documentation for classAsyncFeatureSpec.Class fixture.AsyncFeatureSpecbehaves similarly to classorg.scalatest.AsyncFeatureSpec, except that tests may have a fixture parameter. The type of the fixture parameter is defined by the abstractFixtureParamtype, which is a member of this class. This class also contains an abstractwithFixturemethod. ThiswithFixturemethod takes aOneArgAsyncTest, which is a nested trait defined as a member of this class.OneArgAsyncTesthas anapplymethod that takes aFixtureParam. Thisapplymethod is responsible for running a test. This class'srunTestmethod delegates the actual running of each test towithFixture(OneArgAsyncTest), passing in the test code to run via theOneArgAsyncTestargument. ThewithFixture(OneArgAsyncTest)method (abstract in this class) is responsible for creating the fixture argument and passing it to the test function.Subclasses of this class must, therefore, do three things differently from a plain old org.scalatest.AsyncFeatureSpec:- define the type of the fixture parameter by specifying type FixtureParam
- define the withFixture(OneArgAsyncTest)method
- write tests that take a fixture parameter
- (You can also define tests that don't take a fixture parameter.)
 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 class. One good approach to passing multiple fixture objects is to encapsulate them in a case class. Here's an example: case class FixtureParam(file: File, writer: FileWriter) To enable the stacking of traits that define withFixture(NoArgAsyncTest), it is a good idea to letwithFixture(NoArgAsyncTest)invoke the test function instead of invoking the test function directly. To do so, you'll need to convert theOneArgAsyncTestto aNoArgAsyncTest. You can do that by passing the fixture object to thetoNoArgAsyncTestmethod ofOneArgAsyncTest. In other words, instead of writing “test(theFixture)”, you'd delegate responsibility for invoking the test function to thewithFixture(NoArgAsyncTest)method of the same instance by writing:withFixture(test.toNoArgAsyncTest(theFixture)) Here's a complete example: package org.scalatest.examples.asyncfeaturespec.oneargasynctest 
 import org.scalatest._ import scala.concurrent.Future import scala.concurrent.ExecutionContext
 // Defining actor messages sealed abstract class StringOp case object Clear extends StringOp case class Append(value: String) extends StringOp case object GetValue
 class StringActor { // Simulating an actor private final val sb = new StringBuilder def !(op: StringOp): Unit = synchronized { op match { case Append(value) => sb.append(value) case Clear => sb.clear() } } def ?(get: GetValue.type)(implicit c: ExecutionContext): Future[String] = Future { synchronized { sb.toString } } }
 class ExampleSpec extends fixture.AsyncFeatureSpec {
 type FixtureParam = StringActor
 def withFixture(test: OneArgAsyncTest): FutureOutcome = {
 val actor = new StringActor complete { actor ! Append("ScalaTest is designed to ") // set up the fixture withFixture(test.toNoArgAsyncTest(actor)) } lastly { actor ! Clear // ensure the fixture will be cleaned up } }
 feature("Simplicity") { scenario("User needs to read test code written by others") { actor => actor ! Append("encourage clear code!") val futureString = actor ? GetValue futureString map { s => assert(s === "ScalaTest is designed to encourage clear code!") } }
 scenario("User needs to understand what the tests are doing") { actor => actor ! Append("be easy to reason about!") val futureString = actor ? GetValue futureString map { s => assert(s === "ScalaTest is designed to be easy to reason about!") } } } }If a test fails, the future returned by the OneArgAsyncTestfunction will result in an org.scalatest.Failed wrapping the exception describing the failure. To ensure clean up happens even if a test fails, you should invoke the test function and do the cleanup usingcomplete-lastly, as shown in the previous example. Thecomplete-lastlysyntax, defined inCompleteLastly, which is extended byAsyncTestSuite, ensures the second, cleanup block of code is executed, whether the the first block throws an exception or returns a future. If it returns a future, the cleanup will be executed when the future completes.Sharing fixtures across classesIf multiple test classes need the same fixture, you can define the FixtureParamandwithFixture(OneArgAsyncTest)implementations in a trait, then mix that trait into the test classes that need it. For example, if your application requires a database and your integration tests use that database, you will likely have many test classes that need a database fixture. You can create a "database fixture" trait that creates a database with a unique name, passes the connector into the test, then removes the database once the test completes. This is shown in the following example:* package org.scalatest.examples.fixture.asyncfeaturespec.sharing 
 import java.util.concurrent.ConcurrentHashMap import org.scalatest._ import DbServer._ import java.util.UUID.randomUUID import scala.concurrent.Future
 object DbServer { // Simulating a database server type Db = StringBuffer private val databases = new ConcurrentHashMap[String, Db] def createDb(name: String): Db = { val db = new StringBuffer databases.put(name, db) db } def removeDb(name: String) { databases.remove(name) } }
 trait DbFixture { this: fixture.AsyncTestSuite =>
 type FixtureParam = Db
 // Allow clients to populate the database after // it is created def populateDb(db: Db) {}
 def withFixture(test: OneArgAsyncTest): FutureOutcome = { val dbName = randomUUID.toString val db = createDb(dbName) // create the fixture complete { populateDb(db) // setup the fixture withFixture(test.toNoArgAsyncTest(db)) // "loan" the fixture to the test } lastly { removeDb(dbName) // ensure the fixture will be cleaned up } } }
 class ExampleSpec extends fixture.AsyncFeatureSpec with DbFixture {
 override def populateDb(db: Db) { // setup the fixture db.append("ScalaTest is ") }
 feature("Simplicity") { scenario("Testing should be easy to write") { db => Future { db.append("easy to write!") assert(db.toString === "ScalaTest is easy to write!") } }
 scenario("Testing should be fun") { db => Future { db.append("fun to write!") assert(db.toString === "ScalaTest is fun to write!") } }
 // This test doesn't need a Db scenario("Testing code should be clear") { () => Future { val buf = new StringBuffer buf.append("ScalaTest code is ") buf.append("clear!") assert(buf.toString === "ScalaTest code is clear!") } } } }Often when you create fixtures in a trait like DbFixture, you'll still need to enable individual test classes to "setup" a newly created fixture before it gets passed into the tests. A good way to accomplish this is to pass the newly created fixture into a setup method, likepopulateDbin the previous example, before passing it to the test function. Classes that need to perform such setup can override the method, as doesExampleSuite.If a test doesn't need the fixture, you can indicate that by providing a no-arg instead of a one-arg function, as is done in the third test in the previous example, “ test code should be clear”. In other words, instead of starting your function literal with something like “db =>”, you'd start it with “() =>”. For such tests,runTestwill not invokewithFixture(OneArgAsyncTest). It will instead directly invokewithFixture(NoArgAsyncTest).Both examples shown above demonstrate the technique of giving each test its own "fixture sandbox" to play in. When your fixtures involve external side-effects, like creating files or databases, it is a good idea to give each file or database a unique name as is done in these examples. This keeps tests completely isolated, allowing you to run them in parallel if desired. You could mix ParallelTestExecutioninto either of theseExampleSuiteclasses, and the tests would run in parallel just fine.
- define the type of the fixture parameter by specifying type 
-    trait AsyncFeatureSpecLike extends AsyncTestSuite with AsyncTestRegistration with Informing with Notifying with Alerting with DocumentingImplementation trait for class fixture.AsyncFeatureSpec, which is a sister class toorg.scalatest.AsyncFeatureSpecthat can pass a fixture object into its tests.Implementation trait for class fixture.AsyncFeatureSpec, which is a sister class toorg.scalatest.AsyncFeatureSpecthat can pass a fixture object into its tests.fixture.AsyncFeatureSpecis a class, not a trait, to minimize compile time given there is a slight compiler overhead to mixing in traits compared to extending classes. If you need to mix the behavior offixture.AsyncFeatureSpecinto some other class, you can use this trait instead, because classfixture.AsyncFeatureSpecdoes nothing more than extend this trait and add a nicetoStringimplementation.See the documentation of the class for a detailed overview of fixture.AsyncFeatureSpec.
-   abstract  class AsyncFlatSpec extends AsyncFlatSpecLikeA sister class to org.scalatest.AsyncFlatSpecthat can pass a fixture object into its tests.A sister class to org.scalatest.AsyncFlatSpecthat can pass a fixture object into its tests.Recommended Usage: Use class fixture.AsyncFlatSpecin situations for whichAsyncFlatSpecwould be a good choice, when all or most tests need the same fixture objects that must be cleaned up afterwards. Note:fixture.AsyncFlatSpecis intended for use in special situations, with classAsyncFlatSpecused for general needs. For more insight into wherefixture.AsyncFlatSpecfits in the big picture, see thewithFixture(OneArgAsyncTest)subsection of the Shared fixtures section in the documentation for classAsyncFlatSpec.Class fixture.AsyncFlatSpecbehaves similarly to classorg.scalatest.AsyncFlatSpec, except that tests may have a fixture parameter. The type of the fixture parameter is defined by the abstractFixtureParamtype, which is a member of this class. This class also contains an abstractwithFixturemethod. ThiswithFixturemethod takes aOneArgAsyncTest, which is a nested trait defined as a member of this class.OneArgAsyncTesthas anapplymethod that takes aFixtureParam. Thisapplymethod is responsible for running a test. This class'srunTestmethod delegates the actual running of each test towithFixture(OneArgAsyncTest), passing in the test code to run via theOneArgAsyncTestargument. ThewithFixture(OneArgAsyncTest)method (abstract in this class) is responsible for creating the fixture argument and passing it to the test function.Subclasses of this class must, therefore, do three things differently from a plain old org.scalatest.AsyncFlatSpec:- define the type of the fixture parameter by specifying type FixtureParam
- define the withFixture(OneArgAsyncTest)method
- write tests that take a fixture parameter
- (You can also define tests that don't take a fixture parameter.)
 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 class. One good approach to passing multiple fixture objects is to encapsulate them in a case class. Here's an example: case class FixtureParam(file: File, writer: FileWriter) To enable the stacking of traits that define withFixture(NoArgAsyncTest), it is a good idea to letwithFixture(NoArgAsyncTest)invoke the test function instead of invoking the test function directly. To do so, you'll need to convert theOneArgAsyncTestto aNoArgAsyncTest. You can do that by passing the fixture object to thetoNoArgAsyncTestmethod ofOneArgAsyncTest. In other words, instead of writing “test(theFixture)”, you'd delegate responsibility for invoking the test function to thewithFixture(NoArgAsyncTest)method of the same instance by writing:withFixture(test.toNoArgAsyncTest(theFixture)) Here's a complete example: package org.scalatest.examples.asyncflatspec.oneargasynctest 
 import org.scalatest._ import scala.concurrent.Future import scala.concurrent.ExecutionContext
 // Defining actor messages sealed abstract class StringOp case object Clear extends StringOp case class Append(value: String) extends StringOp case object GetValue
 class StringActor { // Simulating an actor private final val sb = new StringBuilder def !(op: StringOp): Unit = synchronized { op match { case Append(value) => sb.append(value) case Clear => sb.clear() } } def ?(get: GetValue.type)(implicit c: ExecutionContext): Future[String] = Future { synchronized { sb.toString } } }
 class ExampleSpec extends fixture.AsyncFlatSpec {
 type FixtureParam = StringActor
 def withFixture(test: OneArgAsyncTest): FutureOutcome = {
 val actor = new StringActor complete { actor ! Append("ScalaTest is ") // set up the fixture withFixture(test.toNoArgAsyncTest(actor)) } lastly { actor ! Clear // ensure the fixture will be cleaned up } }
 "Testing" should "be easy" in { actor => actor ! Append("easy!") val futureString = actor ? GetValue futureString map { s => assert(s == "ScalaTest is easy!") } }
 it should "be fun" in { actor => actor ! Append("fun!") val futureString = actor ? GetValue futureString map { s => assert(s == "ScalaTest is fun!") } }
 }If a test fails, the future returned by the OneArgAsyncTestfunction will result in an org.scalatest.Failed wrapping the exception describing the failure. To ensure clean up happens even if a test fails, you should invoke the test function and do the cleanup usingcomplete-lastly, as shown in the previous example. Thecomplete-lastlysyntax, defined inCompleteLastly, which is extended byAsyncTestSuite, ensures the second, cleanup block of code is executed, whether the the first block throws an exception or returns a future. If it returns a future, the cleanup will be executed when the future completes.Sharing fixtures across classesIf multiple test classes need the same fixture, you can define the FixtureParamandwithFixture(OneArgAsyncTest)implementations in a trait, then mix that trait into the test classes that need it. For example, if your application requires a database and your integration tests use that database, you will likely have many test classes that need a database fixture. You can create a "database fixture" trait that creates a database with a unique name, passes the connector into the test, then removes the database once the test completes. This is shown in the following example:package org.scalatest.examples.fixture.asyncflatspec.sharing 
 import java.util.concurrent.ConcurrentHashMap import org.scalatest._ import DbServer._ import java.util.UUID.randomUUID import scala.concurrent.Future
 object DbServer { // Simulating a database server type Db = StringBuffer private val databases = new ConcurrentHashMap[String, Db] def createDb(name: String): Db = { val db = new StringBuffer databases.put(name, db) db } def removeDb(name: String) { databases.remove(name) } }
 trait DbFixture { this: fixture.AsyncTestSuite =>
 type FixtureParam = Db
 // Allow clients to populate the database after // it is created def populateDb(db: Db) {}
 def withFixture(test: OneArgAsyncTest): FutureOutcome = { val dbName = randomUUID.toString val db = createDb(dbName) // create the fixture complete { populateDb(db) // setup the fixture withFixture(test.toNoArgAsyncTest(db)) // "loan" the fixture to the test } lastly { removeDb(dbName) // ensure the fixture will be cleaned up } } }
 class ExampleSpec extends fixture.AsyncFlatSpec with DbFixture {
 override def populateDb(db: Db) { // setup the fixture db.append("ScalaTest is ") }
 "Testing" should "should be easy" in { db => Future { db.append("easy!") assert(db.toString === "ScalaTest is easy!") } }
 it should "be fun" in { db => Future { db.append("fun!") assert(db.toString === "ScalaTest is fun!") } }
 // This test doesn't need a Db "Test code" should "be clear" in { () => Future { val buf = new StringBuffer buf.append("ScalaTest code is ") buf.append("clear!") assert(buf.toString === "ScalaTest code is clear!") } } }Often when you create fixtures in a trait like DbFixture, you'll still need to enable individual test classes to "setup" a newly created fixture before it gets passed into the tests. A good way to accomplish this is to pass the newly created fixture into a setup method, likepopulateDbin the previous example, before passing it to the test function. Classes that need to perform such setup can override the method, as doesExampleSuite.If a test doesn't need the fixture, you can indicate that by providing a no-arg instead of a one-arg function, as is done in the third test in the previous example, “ test code should be clear”. In other words, instead of starting your function literal with something like “db =>”, you'd start it with “() =>”. For such tests,runTestwill not invokewithFixture(OneArgAsyncTest). It will instead directly invokewithFixture(NoArgAsyncTest).Both examples shown above demonstrate the technique of giving each test its own "fixture sandbox" to play in. When your fixtures involve external side-effects, like creating files or databases, it is a good idea to give each file or database a unique name as is done in these examples. This keeps tests completely isolated, allowing you to run them in parallel if desired. You could mix ParallelTestExecutioninto either of theseExampleSuiteclasses, and the tests would run in parallel just fine.
- define the type of the fixture parameter by specifying type 
-    trait AsyncFlatSpecLike extends AsyncTestSuite with AsyncTestRegistration with ShouldVerb with MustVerb with CanVerb with Informing with Notifying with Alerting with DocumentingImplementation trait for class fixture.AsyncFlatSpec, which is a sister class toorg.scalatest.AsyncFlatSpecthat can pass a fixture object into its tests.Implementation trait for class fixture.AsyncFlatSpec, which is a sister class toorg.scalatest.AsyncFlatSpecthat can pass a fixture object into its tests.fixture.AsyncFlatSpecis a class, not a trait, to minimize compile time given there is a slight compiler overhead to mixing in traits compared to extending classes. If you need to mix the behavior offixture.AsyncFlatSpecinto some other class, you can use this trait instead, because classfixture.AsyncFlatSpecdoes nothing more than extend this trait and add a nicetoStringimplementation.See the documentation of the class for a detailed overview of fixture.AsyncFlatSpec.
-   abstract  class AsyncFreeSpec extends AsyncFreeSpecLikeA sister class to org.scalatest.AsyncFunSpecthat can pass a fixture object into its tests.A sister class to org.scalatest.AsyncFunSpecthat can pass a fixture object into its tests.Recommended Usage: Use class fixture.AsyncFunSpecin situations for whichAsyncFunSpecwould be a good choice, when all or most tests need the same fixture objects that must be cleaned up afterwards. Note:fixture.AsyncFunSpecis intended for use in special situations, with classAsyncFunSpecused for general needs. For more insight into wherefixture.AsyncFunSpecfits in the big picture, see thewithFixture(OneArgAsyncTest)subsection of the Shared fixtures section in the documentation for classAsyncFunSpec.Class fixture.AsyncFunSpecbehaves similarly to classorg.scalatest.AsyncFunSpec, except that tests may have a fixture parameter. The type of the fixture parameter is defined by the abstractFixtureParamtype, which is a member of this class. This class also contains an abstractwithFixturemethod. ThiswithFixturemethod takes aOneArgAsyncTest, which is a nested trait defined as a member of this class.OneArgAsyncTesthas anapplymethod that takes aFixtureParam. Thisapplymethod is responsible for running a test. This class'srunTestmethod delegates the actual running of each test towithFixture(OneArgAsyncTest), passing in the test code to run via theOneArgAsyncTestargument. ThewithFixture(OneArgAsyncTest)method (abstract in this class) is responsible for creating the fixture argument and passing it to the test function.Subclasses of this class must, therefore, do three things differently from a plain old org.scalatest.AsyncFunSpec:- define the type of the fixture parameter by specifying type FixtureParam
- define the withFixture(OneArgAsyncTest)method
- write tests that take a fixture parameter
- (You can also define tests that don't take a fixture parameter.)
 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 class. One good approach to passing multiple fixture objects is to encapsulate them in a case class. Here's an example: case class FixtureParam(file: File, writer: FileWriter) To enable the stacking of traits that define withFixture(NoArgAsyncTest), it is a good idea to letwithFixture(NoArgAsyncTest)invoke the test function instead of invoking the test function directly. To do so, you'll need to convert theOneArgAsyncTestto aNoArgAsyncTest. You can do that by passing the fixture object to thetoNoArgAsyncTestmethod ofOneArgAsyncTest. In other words, instead of writing “test(theFixture)”, you'd delegate responsibility for invoking the test function to thewithFixture(NoArgAsyncTest)method of the same instance by writing:withFixture(test.toNoArgAsyncTest(theFixture)) Here's a complete example: package org.scalatest.examples.asyncfreespec.oneargasynctest 
 import org.scalatest._ import scala.concurrent.Future import scala.concurrent.ExecutionContext
 // Defining actor messages sealed abstract class StringOp case object Clear extends StringOp case class Append(value: String) extends StringOp case object GetValue
 class StringActor { // Simulating an actor private final val sb = new StringBuilder def !(op: StringOp): Unit = synchronized { op match { case Append(value) => sb.append(value) case Clear => sb.clear() } } def ?(get: GetValue.type)(implicit c: ExecutionContext): Future[String] = Future { synchronized { sb.toString } } }
 class ExampleSpec extends fixture.AsyncFreeSpec {
 type FixtureParam = StringActor
 def withFixture(test: OneArgAsyncTest): FutureOutcome = {
 val actor = new StringActor complete { actor ! Append("ScalaTest is ") // set up the fixture withFixture(test.toNoArgAsyncTest(actor)) } lastly { actor ! Clear // ensure the fixture will be cleaned up } }
 "Testing" - { "should be easy" in { actor => actor ! Append("easy!") val futureString = actor ? GetValue futureString map { s => assert(s == "ScalaTest is easy!") } }
 "should be fun" in { actor => actor ! Append("fun!") val futureString = actor ? GetValue futureString map { s => assert(s == "ScalaTest is fun!") } } } }If a test fails, the future returned by the OneArgAsyncTestfunction will result in an org.scalatest.Failed wrapping the exception describing the failure. To ensure clean up happens even if a test fails, you should invoke the test function and do the cleanup usingcomplete-lastly, as shown in the previous example. Thecomplete-lastlysyntax, defined inCompleteLastly, which is extended byAsyncTestSuite, ensures the second, cleanup block of code is executed, whether the the first block throws an exception or returns a future. If it returns a future, the cleanup will be executed when the future completes.Sharing fixtures across classesIf multiple test classes need the same fixture, you can define the FixtureParamandwithFixture(OneArgAsyncTest)implementations in a trait, then mix that trait into the test classes that need it. For example, if your application requires a database and your integration tests use that database, you will likely have many test classes that need a database fixture. You can create a "database fixture" trait that creates a database with a unique name, passes the connector into the test, then removes the database once the test completes. This is shown in the following example:package org.scalatest.examples.fixture.asyncfreespec.sharing 
 import java.util.concurrent.ConcurrentHashMap import org.scalatest._ import DbServer._ import java.util.UUID.randomUUID import scala.concurrent.Future
 object DbServer { // Simulating a database server type Db = StringBuffer private val databases = new ConcurrentHashMap[String, Db] def createDb(name: String): Db = { val db = new StringBuffer databases.put(name, db) db } def removeDb(name: String) { databases.remove(name) } }
 trait DbFixture { this: fixture.AsyncTestSuite =>
 type FixtureParam = Db
 // Allow clients to populate the database after // it is created def populateDb(db: Db) {}
 def withFixture(test: OneArgAsyncTest): FutureOutcome = { val dbName = randomUUID.toString val db = createDb(dbName) // create the fixture complete { populateDb(db) // setup the fixture withFixture(test.toNoArgAsyncTest(db)) // "loan" the fixture to the test } lastly { removeDb(dbName) // ensure the fixture will be cleaned up } } }
 class ExampleSpec extends fixture.AsyncFreeSpec with DbFixture {
 override def populateDb(db: Db) { // setup the fixture db.append("ScalaTest is ") }
 "Testing" - { "should be easy" in { db => Future { db.append("easy!") assert(db.toString === "ScalaTest is easy!") } }
 "should be fun" in { db => Future { db.append("fun!") assert(db.toString === "ScalaTest is fun!") } }
 // This test doesn't need a Db "code should be clear" in { () => Future { val buf = new StringBuffer buf.append("ScalaTest code is ") buf.append("clear!") assert(buf.toString === "ScalaTest code is clear!") } } } }Often when you create fixtures in a trait like DbFixture, you'll still need to enable individual test classes to "setup" a newly created fixture before it gets passed into the tests. A good way to accomplish this is to pass the newly created fixture into a setup method, likepopulateDbin the previous example, before passing it to the test function. Classes that need to perform such setup can override the method, as doesExampleSuite.If a test doesn't need the fixture, you can indicate that by providing a no-arg instead of a one-arg function, as is done in the third test in the previous example, “ test code should be clear”. In other words, instead of starting your function literal with something like “db =>”, you'd start it with “() =>”. For such tests,runTestwill not invokewithFixture(OneArgAsyncTest). It will instead directly invokewithFixture(NoArgAsyncTest).Both examples shown above demonstrate the technique of giving each test its own "fixture sandbox" to play in. When your fixtures involve external side-effects, like creating files or databases, it is a good idea to give each file or database a unique name as is done in these examples. This keeps tests completely isolated, allowing you to run them in parallel if desired. You could mix ParallelTestExecutioninto either of theseExampleSuiteclasses, and the tests would run in parallel just fine.
- define the type of the fixture parameter by specifying type 
-    trait AsyncFreeSpecLike extends AsyncTestSuite with AsyncTestRegistration with Informing with Notifying with Alerting with DocumentingImplementation trait for class fixture.AsyncFreeSpec, which is a sister class toorg.scalatest.AsyncFreeSpecthat can pass a fixture object into its tests.Implementation trait for class fixture.AsyncFreeSpec, which is a sister class toorg.scalatest.AsyncFreeSpecthat can pass a fixture object into its tests.fixture.AsyncFreeSpecis a class, not a trait, to minimize compile time given there is a slight compiler overhead to mixing in traits compared to extending classes. If you need to mix the behavior offixture.AsyncFreeSpecinto some other class, you can use this trait instead, because classfixture.AsyncFreeSpecdoes nothing more than extend this trait and add a nicetoStringimplementation.See the documentation of the class for a detailed overview of fixture.AsyncFreeSpec.
-   abstract  class AsyncFunSpec extends AsyncFunSpecLikeA sister class to org.scalatest.AsyncFunSpecthat can pass a fixture object into its tests.A sister class to org.scalatest.AsyncFunSpecthat can pass a fixture object into its tests.Recommended Usage: Use class fixture.AsyncFunSpecin situations for whichAsyncFunSpecwould be a good choice, when all or most tests need the same fixture objects that must be cleaned up afterwards. Note:fixture.AsyncFunSpecis intended for use in special situations, with classAsyncFunSpecused for general needs. For more insight into wherefixture.AsyncFunSpecfits in the big picture, see thewithFixture(OneArgAsyncTest)subsection of the Shared fixtures section in the documentation for classAsyncFunSpec.Class fixture.AsyncFunSpecbehaves similarly to classorg.scalatest.AsyncFunSpec, except that tests may have a fixture parameter. The type of the fixture parameter is defined by the abstractFixtureParamtype, which is a member of this class. This class also contains an abstractwithFixturemethod. ThiswithFixturemethod takes aOneArgAsyncTest, which is a nested trait defined as a member of this class.OneArgAsyncTesthas anapplymethod that takes aFixtureParam. Thisapplymethod is responsible for running a test. This class'srunTestmethod delegates the actual running of each test towithFixture(OneArgAsyncTest), passing in the test code to run via theOneArgAsyncTestargument. ThewithFixture(OneArgAsyncTest)method (abstract in this class) is responsible for creating the fixture argument and passing it to the test function.Subclasses of this class must, therefore, do three things differently from a plain old org.scalatest.AsyncFunSpec:- define the type of the fixture parameter by specifying type FixtureParam
- define the withFixture(OneArgAsyncTest)method
- write tests that take a fixture parameter
- (You can also define tests that don't take a fixture parameter.)
 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 class. One good approach to passing multiple fixture objects is to encapsulate them in a case class. Here's an example: case class FixtureParam(file: File, writer: FileWriter) To enable the stacking of traits that define withFixture(NoArgAsyncTest), it is a good idea to letwithFixture(NoArgAsyncTest)invoke the test function instead of invoking the test function directly. To do so, you'll need to convert theOneArgAsyncTestto aNoArgAsyncTest. You can do that by passing the fixture object to thetoNoArgAsyncTestmethod ofOneArgAsyncTest. In other words, instead of writing “test(theFixture)”, you'd delegate responsibility for invoking the test function to thewithFixture(NoArgAsyncTest)method of the same instance by writing:withFixture(test.toNoArgAsyncTest(theFixture)) Here's a complete example: package org.scalatest.examples.asyncfunspec.oneargasynctest 
 import org.scalatest._ import scala.concurrent.Future import scala.concurrent.ExecutionContext
 // Defining actor messages sealed abstract class StringOp case object Clear extends StringOp case class Append(value: String) extends StringOp case object GetValue
 class StringActor { // Simulating an actor private final val sb = new StringBuilder def !(op: StringOp): Unit = synchronized { op match { case Append(value) => sb.append(value) case Clear => sb.clear() } } def ?(get: GetValue.type)(implicit c: ExecutionContext): Future[String] = Future { synchronized { sb.toString } } }
 class ExampleSpec extends fixture.AsyncFunSpec {
 type FixtureParam = StringActor
 def withFixture(test: OneArgAsyncTest): FutureOutcome = {
 val actor = new StringActor complete { actor ! Append("ScalaTest is ") // set up the fixture withFixture(test.toNoArgAsyncTest(actor)) } lastly { actor ! Clear // ensure the fixture will be cleaned up } }
 describe("Testing") { it("should be easy") { actor => actor ! Append("easy!") val futureString = actor ? GetValue futureString map { s => assert(s == "ScalaTest is easy!") } }
 it("should be fun") { actor => actor ! Append("fun!") val futureString = actor ? GetValue futureString map { s => assert(s == "ScalaTest is fun!") } } } }If a test fails, the future returned by the OneArgAsyncTestfunction will result in an org.scalatest.Failed wrapping the exception describing the failure. To ensure clean up happens even if a test fails, you should invoke the test function and do the cleanup usingcomplete-lastly, as shown in the previous example. Thecomplete-lastlysyntax, defined inCompleteLastly, which is extended byAsyncTestSuite, ensures the second, cleanup block of code is executed, whether the the first block throws an exception or returns a future. If it returns a future, the cleanup will be executed when the future completes.Sharing fixtures across classesIf multiple test classes need the same fixture, you can define the FixtureParamandwithFixture(OneArgAsyncTest)implementations in a trait, then mix that trait into the test classes that need it. For example, if your application requires a database and your integration tests use that database, you will likely have many test classes that need a database fixture. You can create a "database fixture" trait that creates a database with a unique name, passes the connector into the test, then removes the database once the test completes. This is shown in the following example:package org.scalatest.examples.fixture.asyncfunspec.sharing 
 import java.util.concurrent.ConcurrentHashMap import org.scalatest._ import DbServer._ import java.util.UUID.randomUUID import scala.concurrent.Future
 object DbServer { // Simulating a database server type Db = StringBuffer private val databases = new ConcurrentHashMap[String, Db] def createDb(name: String): Db = { val db = new StringBuffer databases.put(name, db) db } def removeDb(name: String) { databases.remove(name) } }
 trait DbFixture { this: fixture.AsyncTestSuite =>
 type FixtureParam = Db
 // Allow clients to populate the database after // it is created def populateDb(db: Db) {}
 def withFixture(test: OneArgAsyncTest): FutureOutcome = { val dbName = randomUUID.toString val db = createDb(dbName) // create the fixture complete { populateDb(db) // setup the fixture withFixture(test.toNoArgAsyncTest(db)) // "loan" the fixture to the test } lastly { removeDb(dbName) // ensure the fixture will be cleaned up } } }
 class ExampleSpec extends fixture.AsyncFunSpec with DbFixture {
 override def populateDb(db: Db) { // setup the fixture db.append("ScalaTest is ") }
 describe("testing") { it("should be easy") { db => Future { db.append("easy!") assert(db.toString === "ScalaTest is easy!") } }
 it("should be fun") { db => Future { db.append("fun!") assert(db.toString === "ScalaTest is fun!") } }
 // This test doesn't need a Db it("code should be clear") { () => Future { val buf = new StringBuffer buf.append("ScalaTest code is ") buf.append("clear!") assert(buf.toString === "ScalaTest code is clear!") } } } }Often when you create fixtures in a trait like DbFixture, you'll still need to enable individual test classes to "setup" a newly created fixture before it gets passed into the tests. A good way to accomplish this is to pass the newly created fixture into a setup method, likepopulateDbin the previous example, before passing it to the test function. Classes that need to perform such setup can override the method, as doesExampleSuite.If a test doesn't need the fixture, you can indicate that by providing a no-arg instead of a one-arg function, as is done in the third test in the previous example, “ test code should be clear”. In other words, instead of starting your function literal with something like “db =>”, you'd start it with “() =>”. For such tests,runTestwill not invokewithFixture(OneArgAsyncTest). It will instead directly invokewithFixture(NoArgAsyncTest).Both examples shown above demonstrate the technique of giving each test its own "fixture sandbox" to play in. When your fixtures involve external side-effects, like creating files or databases, it is a good idea to give each file or database a unique name as is done in these examples. This keeps tests completely isolated, allowing you to run them in parallel if desired. You could mix ParallelTestExecutioninto either of theseExampleSuiteclasses, and the tests would run in parallel just fine.
- define the type of the fixture parameter by specifying type 
-    trait AsyncFunSpecLike extends AsyncTestSuite with AsyncTestRegistration with Informing with Notifying with Alerting with DocumentingImplementation trait for class fixture.AsyncFunSpec, which is a sister class toorg.scalatest.AsyncFunSpecthat can pass a fixture object into its tests.Implementation trait for class fixture.AsyncFunSpec, which is a sister class toorg.scalatest.AsyncFunSpecthat can pass a fixture object into its tests.fixture.AsyncFunSpecis a class, not a trait, to minimize compile time given there is a slight compiler overhead to mixing in traits compared to extending classes. If you need to mix the behavior offixture.AsyncFunSpecinto some other class, you can use this trait instead, because classfixture.AsyncFunSpecdoes nothing more than extend this trait and add a nicetoStringimplementation.See the documentation of the class for a detailed overview of fixture.AsyncFunSpec.
-   abstract  class AsyncFunSuite extends AsyncFunSuiteLikeA sister class to org.scalatest.AsyncFunSuitethat can pass a fixture object into its tests.A sister class to org.scalatest.AsyncFunSuitethat can pass a fixture object into its tests.Recommended Usage: Use class fixture.AsyncFunSuitein situations for whichAsyncFunSuitewould be a good choice, when all or most tests need the same fixture objects that must be cleaned up afterwards. Note:fixture.AsyncFunSuiteis intended for use in special situations, with classAsyncFunSuiteused for general needs. For more insight into wherefixture.AsyncFunSuitefits in the big picture, see thewithFixture(OneArgAsyncTest)subsection of the Shared fixtures section in the documentation for classAsyncFunSuite.Class fixture.AsyncFunSuitebehaves similarly to classorg.scalatest.AsyncFunSuite, except that tests may have a fixture parameter. The type of the fixture parameter is defined by the abstractFixtureParamtype, which is a member of this class. This class also contains an abstractwithFixturemethod. ThiswithFixturemethod takes aOneArgAsyncTest, which is a nested trait defined as a member of this class.OneArgAsyncTesthas anapplymethod that takes aFixtureParam. Thisapplymethod is responsible for running a test. This class'srunTestmethod delegates the actual running of each test towithFixture(OneArgAsyncTest), passing in the test code to run via theOneArgAsyncTestargument. ThewithFixture(OneArgAsyncTest)method (abstract in this class) is responsible for creating the fixture argument and passing it to the test function.Subclasses of this class must, therefore, do three things differently from a plain old org.scalatest.AsyncFunSuite:- define the type of the fixture parameter by specifying type FixtureParam
- define the withFixture(OneArgAsyncTest)method
- write tests that take a fixture parameter
- (You can also define tests that don't take a fixture parameter.)
 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 class. One good approach to passing multiple fixture objects is to encapsulate them in a case class. Here's an example: case class FixtureParam(file: File, writer: FileWriter) To enable the stacking of traits that define withFixture(NoArgAsyncTest), it is a good idea to letwithFixture(NoArgAsyncTest)invoke the test function instead of invoking the test function directly. To do so, you'll need to convert theOneArgAsyncTestto aNoArgAsyncTest. You can do that by passing the fixture object to thetoNoArgAsyncTestmethod ofOneArgAsyncTest. In other words, instead of writing “test(theFixture)”, you'd delegate responsibility for invoking the test function to thewithFixture(NoArgAsyncTest)method of the same instance by writing:withFixture(test.toNoArgAsyncTest(theFixture)) Here's a complete example: package org.scalatest.examples.asyncfunsuite.oneargasynctest 
 import org.scalatest._ import java.io._ import scala.concurrent.Future import scala.concurrent.ExecutionContext
 // Defining actor messages sealed abstract class StringOp case object Clear extends StringOp case class Append(value: String) extends StringOp case object GetValue
 class StringActor { // Simulating an actor private final val sb = new StringBuilder def !(op: StringOp): Unit = synchronized { op match { case Append(value) => sb.append(value) case Clear => sb.clear() } } def ?(get: GetValue.type)(implicit c: ExecutionContext): Future[String] = Future { synchronized { sb.toString } } }
 class ExampleSuite extends fixture.AsyncFunSuite {
 type FixtureParam = StringActor
 def withFixture(test: OneArgAsyncTest): FutureOutcome = {
 val actor = new StringActor complete { actor ! Append("ScalaTest is ") // set up the fixture withFixture(test.toNoArgAsyncTest(actor)) } lastly { actor ! Clear // ensure the fixture will be cleaned up } }
 test("Testing should be easy") { actor => actor ! Append("easy!") val futureString = actor ? GetValue futureString map { s => assert(s === "ScalaTest is easy!") } }
 test("Testing should be fun") { actor => actor ! Append("fun!") val futureString = actor ? GetValue futureString map { s => assert(s === "ScalaTest is fun!") } } }If a test fails, the future returned by the OneArgAsyncTestfunction will result in an org.scalatest.Failed wrapping the exception describing the failure. To ensure clean up happens even if a test fails, you should invoke the test function and do the cleanup usingcomplete-lastly, as shown in the previous example. Thecomplete-lastlysyntax, defined inCompleteLastly, which is extended byAsyncTestSuite, ensures the second, cleanup block of code is executed, whether the the first block throws an exception or returns a future. If it returns a future, the cleanup will be executed when the future completes.Sharing fixtures across classesIf multiple test classes need the same fixture, you can define the FixtureParamandwithFixture(OneArgAsyncTest)implementations in a trait, then mix that trait into the test classes that need it. For example, if your application requires a database and your integration tests use that database, you will likely have many test classes that need a database fixture. You can create a "database fixture" trait that creates a database with a unique name, passes the connector into the test, then removes the database once the test completes. This is shown in the following example:package org.scalatest.examples.fixture.asyncfunsuite.sharing 
 import java.util.concurrent.ConcurrentHashMap import org.scalatest._ import DbServer._ import java.util.UUID.randomUUID import scala.concurrent.Future
 object DbServer { // Simulating a database server type Db = StringBuffer private val databases = new ConcurrentHashMap[String, Db] def createDb(name: String): Db = { val db = new StringBuffer databases.put(name, db) db } def removeDb(name: String) { databases.remove(name) } }
 trait DbFixture { this: fixture.AsyncTestSuite =>
 type FixtureParam = Db
 // Allow clients to populate the database after // it is created def populateDb(db: Db) {}
 def withFixture(test: OneArgAsyncTest): FutureOutcome = { val dbName = randomUUID.toString val db = createDb(dbName) // create the fixture complete { populateDb(db) // setup the fixture withFixture(test.toNoArgAsyncTest(db)) // "loan" the fixture to the test } lastly { removeDb(dbName) // ensure the fixture will be cleaned up } } }
 class ExampleSuite extends fixture.AsyncFunSuite with DbFixture {
 override def populateDb(db: Db) { // setup the fixture db.append("ScalaTest is ") }
 test("testing should be easy") { db => Future { db.append("easy!") assert(db.toString === "ScalaTest is easy!") } }
 test("testing should be fun") { db => Future { db.append("fun!") assert(db.toString === "ScalaTest is fun!") } }
 // This test doesn't need a Db test("test code should be clear") { () => Future { val buf = new StringBuffer buf.append("ScalaTest code is ") buf.append("clear!") assert(buf.toString === "ScalaTest code is clear!") } } }Often when you create fixtures in a trait like DbFixture, you'll still need to enable individual test classes to "setup" a newly created fixture before it gets passed into the tests. A good way to accomplish this is to pass the newly created fixture into a setup method, likepopulateDbin the previous example, before passing it to the test function. Classes that need to perform such setup can override the method, as doesExampleSuite.If a test doesn't need the fixture, you can indicate that by providing a no-arg instead of a one-arg function, as is done in the third test in the previous example, “ test code should be clear”. In other words, instead of starting your function literal with something like “db =>”, you'd start it with “() =>”. For such tests,runTestwill not invokewithFixture(OneArgAsyncTest). It will instead directly invokewithFixture(NoArgAsyncTest).Both examples shown above demonstrate the technique of giving each test its own "fixture sandbox" to play in. When your fixtures involve external side-effects, like creating files or databases, it is a good idea to give each file or database a unique name as is done in these examples. This keeps tests completely isolated, allowing you to run them in parallel if desired. You could mix ParallelTestExecutioninto either of theseExampleSuiteclasses, and the tests would run in parallel just fine.
- define the type of the fixture parameter by specifying type 
-    trait AsyncFunSuiteLike extends AsyncTestSuite with AsyncTestRegistration with Informing with Notifying with Alerting with DocumentingImplementation trait for class fixture.AsyncFunSuite, which is a sister class toorg.scalatest.AsyncFunSuitethat can pass a fixture object into its tests.Implementation trait for class fixture.AsyncFunSuite, which is a sister class toorg.scalatest.AsyncFunSuitethat can pass a fixture object into its tests.fixture.AsyncFunSuiteis a class, not a trait, to minimize compile time given there is a slight compiler overhead to mixing in traits compared to extending classes. If you need to mix the behavior offixture.AsyncFunSuiteinto some other class, you can use this trait instead, because classfixture.AsyncFunSuitedoes nothing more than extend this trait and add a nicetoStringimplementation.See the documentation of the class for a detailed overview of fixture.AsyncFunSuite.
-    trait AsyncTestDataFixture extends AnyRefTrait that when mixed into a fixture.AsyncTestSuitepasses theTestDatapassed towithFixtureas a fixture into each test.Trait that when mixed into a fixture.AsyncTestSuitepasses theTestDatapassed towithFixtureas a fixture into each test.For example, here's how you could access the test's name in each test using AsyncTestDataFixture:package org.scalatest.examples.fixture.testdatafixture 
 import org.scalatest._
 class ExampleAsyncSpec extends fixture.AsyncFlatSpec with fixture.AsyncTestDataFixture {
 "Accessing the test data" should "be easy!" in { td => assert(td.name == "Accessing the test data should be easy!") }
 it should "be fun!" in { td => assert(td.name == "Accessing the test data should be fun!") } }
-    trait AsyncTestRegistration extends AnyRefTrait declaring methods that can be used to register test functions that accept a fixture parameter and have result type Future[Assertion].
-    trait AsyncTestSuite extends Suite with scalatest.AsyncTestSuiteThe base trait of ScalaTest's "fixture" async testing styles, which enable you to pass fixture objects into tests. The base trait of ScalaTest's "fixture" async testing styles, which enable you to pass fixture objects into tests. This trait provides a final override of withFixture(OneArgTest), declared in supertraitfixture.Suite, because thewithFixture(OneArgTest)lifecycle method assumes synchronous testing. Here is its signature:def withFixture(test: OneArgTest): Outcome The test function interface, OneArgTest, offers anapplymethod that takes aFixtureParamand returnsOutcome:// In trait OneArgTest: def apply(fixture: FixtureParam): Outcome Because the result of a test is an Outcome, when the test function returns, the test body must have determined an outcome already. It will already be one ofSucceeded,Failed,Canceled, or Pending. This is also true whenwithFixture(OneArgTest)returns: because the result type ofwithFixture(OneArgTest)isOutcome, the test body has by definition has already finished execution.This trait overrides and makes abstract the runTestmethod. Subtraits must must implement this method to callwithFixture(OneArgAsyncTest)instead ofwithFixture(OneArgTest), wherewithFixture(OneArgAsyncTest)is a new method declared in this trait with the following signature and implementation:def withFixture(test: OneArgAsyncTest): FutureOutcome = { test() } Instead of returning OutcomelikewithFixture, thewithFixturemethod returns aFutureOutcome. Similarly, theapplymethod of test function interface,OneArgAsyncTest, returnsFutureOutcome:// In trait OneArgAsyncTest: def apply(fixture: FixtureParam): FutureOutcome The withFixturemethod supports async testing, because when the test function returns, the test body has not necessarily finished execution.The recommended way to ensure cleanup is performed after a test body finishes execution is to use the complete-lastlysyntax, defined in supertraitorg.scalatest.CompleteLastly, which will ensure that cleanup will occur whether future-producing code completes abruptly by throwing an exception, or returns normally yielding a future. In the latter case,complete-lastlywill register the cleanup code to execute asynchronously when the future completes.To enable the stacking of traits that define withFixture(NoArgAsyncTest), it is a good idea to letwithFixture(NoArgAsyncTest)invoke the test function instead of invoking the test function directly. To do so, you'll need to convert theOneArgAsyncTestto aNoArgAsyncTest. You can do that by passing the fixture object to thetoNoArgAsyncTestmethod ofOneArgAsyncTest. In other words, instead of writing “test(theFixture)”, you'd delegate responsibility for invoking the test function to thewithFixture(NoArgAsyncTest)method of the same instance by writing:withFixture(test.toNoArgAsyncTest(theFixture)) Thus, the recommended structure of a withFixtureimplementation that performs cleanup looks like this:// Your implementation override def withFixture(test: OneArgAsyncTest) = { 
 // Perform setup here val theFixture = ...
 complete { withFixture(test.toNoArgAsyncTest(theFixture)) // Invoke the test function } lastly { // Perform cleanup here } }If you have no cleanup to perform, you can write withFixturelike this instead:// Your implementation override def withFixture(test: OneArgAsyncTest) = { 
 // Perform setup here val theFixture = ...
 withFixture(test.toNoArgAsyncTest(theFixture)) // Invoke the test function }If you want to perform an action only for certain outcomes, you'll need to register code performing that action as a callback on the Futureusing one ofFutureregistration methods:onComplete,onSuccess, oronFailure. Note that if a test fails, that will be treated as ascala.util.Success(org.scalatest.Failure). So if you want to perform an action if a test fails, for example, you'd register the callaback usingonSuccess, like this:// Your implementation override def withFixture(test: OneArgAsyncTest) = { 
 // Perform setup here val theFixture = ...
 val futureOutcome = withFixture(test.toNoArgAsyncTest(theFixture)) // Invoke the test function
 futureOutcome onFailedThen { _ => // perform action that you want to occur // only if a test fails here } }Lastly, if you want to transform the outcome in some way in withFixture, you'll need to use either themaportransformmethods ofFuture, like this:// Your implementation override def withFixture(test: OneArgAsyncTest) = { 
 // Perform setup here val theFixture = ...
 val futureOutcome = withFixture(test.toNoArgAsyncTest(theFixture)) // Invoke the test function
 futureOutcome change { outcome => // transform the outcome into a new outcome here } }Note that a NoArgAsyncTest'sapplymethod will only return aFailureif the test completes abruptly with an exception (such asOutOfMemoryError) that should cause the suite to abort rather than the test to fail. Thus usually you would usemapto transform future outcomes, nottransform, so that such suite-aborting exceptions pass through unchanged. The suite will abort asynchronously with any exception returned in aFailure.
-   abstract  class AsyncWordSpec extends AsyncWordSpecLikeA sister class to org.scalatest.AsyncWordSpecthat can pass a fixture object into its tests.A sister class to org.scalatest.AsyncWordSpecthat can pass a fixture object into its tests.Recommended Usage: Use class fixture.AsyncWordSpecin situations for whichAsyncWordSpecwould be a good choice, when all or most tests need the same fixture objects that must be cleaned up afterwards. Note:fixture.AsyncWordSpecis intended for use in special situations, with classAsyncWordSpecused for general needs. For more insight into wherefixture.AsyncWordSpecfits in the big picture, see thewithFixture(OneArgAsyncTest)subsection of the Shared fixtures section in the documentation for classAsyncWordSpec.Class fixture.AsyncWordSpecbehaves similarly to classorg.scalatest.AsyncWordSpec, except that tests may have a fixture parameter. The type of the fixture parameter is defined by the abstractFixtureParamtype, which is a member of this class. This class also contains an abstractwithFixturemethod. ThiswithFixturemethod takes aOneArgAsyncTest, which is a nested trait defined as a member of this class.OneArgAsyncTesthas anapplymethod that takes aFixtureParam. Thisapplymethod is responsible for running a test. This class'srunTestmethod delegates the actual running of each test towithFixture(OneArgAsyncTest), passing in the test code to run via theOneArgAsyncTestargument. ThewithFixture(OneArgAsyncTest)method (abstract in this class) is responsible for creating the fixture argument and passing it to the test function.Subclasses of this class must, therefore, do three things differently from a plain old org.scalatest.AsyncWordSpec:- define the type of the fixture parameter by specifying type FixtureParam
- define the withFixture(OneArgAsyncTest)method
- write tests that take a fixture parameter
- (You can also define tests that don't take a fixture parameter.)
 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 class. One good approach to passing multiple fixture objects is to encapsulate them in a case class. Here's an example: case class FixtureParam(file: File, writer: FileWriter) To enable the stacking of traits that define withFixture(NoArgAsyncTest), it is a good idea to letwithFixture(NoArgAsyncTest)invoke the test function instead of invoking the test function directly. To do so, you'll need to convert theOneArgAsyncTestto aNoArgAsyncTest. You can do that by passing the fixture object to thetoNoArgAsyncTestmethod ofOneArgAsyncTest. In other words, instead of writing “test(theFixture)”, you'd delegate responsibility for invoking the test function to thewithFixture(NoArgAsyncTest)method of the same instance by writing:withFixture(test.toNoArgAsyncTest(theFixture)) Here's a complete example: package org.scalatest.examples.asyncwordspec.oneargasynctest 
 import org.scalatest._ import scala.concurrent.Future import scala.concurrent.ExecutionContext
 // Defining actor messages sealed abstract class StringOp case object Clear extends StringOp case class Append(value: String) extends StringOp case object GetValue
 class StringActor { // Simulating an actor private final val sb = new StringBuilder def !(op: StringOp): Unit = synchronized { op match { case Append(value) => sb.append(value) case Clear => sb.clear() } } def ?(get: GetValue.type)(implicit c: ExecutionContext): Future[String] = Future { synchronized { sb.toString } } }
 class ExampleSpec extends fixture.AsyncWordSpec {
 type FixtureParam = StringActor
 def withFixture(test: OneArgAsyncTest): FutureOutcome = {
 val actor = new StringActor complete { actor ! Append("ScalaTest is ") // set up the fixture withFixture(test.toNoArgAsyncTest(actor)) } lastly { actor ! Clear // ensure the fixture will be cleaned up } }
 "Testing" should { "be easy" in { actor => actor ! Append("easy!") val futureString = actor ? GetValue futureString map { s => assert(s == "ScalaTest is easy!") } }
 "be fun" in { actor => actor ! Append("fun!") val futureString = actor ? GetValue futureString map { s => assert(s == "ScalaTest is fun!") } } } }If a test fails, the future returned by the OneArgAsyncTestfunction will result in an org.scalatest.Failed wrapping the exception describing the failure. To ensure clean up happens even if a test fails, you should invoke the test function and do the cleanup usingcomplete-lastly, as shown in the previous example. Thecomplete-lastlysyntax, defined inCompleteLastly, which is extended byAsyncTestSuite, ensures the second, cleanup block of code is executed, whether the the first block throws an exception or returns a future. If it returns a future, the cleanup will be executed when the future completes.Sharing fixtures across classesIf multiple test classes need the same fixture, you can define the FixtureParamandwithFixture(OneArgAsyncTest)implementations in a trait, then mix that trait into the test classes that need it. For example, if your application requires a database and your integration tests use that database, you will likely have many test classes that need a database fixture. You can create a "database fixture" trait that creates a database with a unique name, passes the connector into the test, then removes the database once the test completes. This is shown in the following example:package org.scalatest.examples.fixture.asyncwordspec.sharing 
 import java.util.concurrent.ConcurrentHashMap import org.scalatest._ import DbServer._ import java.util.UUID.randomUUID import scala.concurrent.Future
 object DbServer { // Simulating a database server type Db = StringBuffer private val databases = new ConcurrentHashMap[String, Db] def createDb(name: String): Db = { val db = new StringBuffer databases.put(name, db) db } def removeDb(name: String) { databases.remove(name) } }
 trait DbFixture { this: fixture.AsyncTestSuite =>
 type FixtureParam = Db
 // Allow clients to populate the database after // it is created def populateDb(db: Db) {}
 def withFixture(test: OneArgAsyncTest): FutureOutcome = { val dbName = randomUUID.toString val db = createDb(dbName) // create the fixture complete { populateDb(db) // setup the fixture withFixture(test.toNoArgAsyncTest(db)) // "loan" the fixture to the test } lastly { removeDb(dbName) // ensure the fixture will be cleaned up } } }
 class ExampleSpec extends fixture.AsyncWordSpec with DbFixture {
 override def populateDb(db: Db) { // setup the fixture db.append("ScalaTest is ") }
 "Testing" should { "be easy" in { db => Future { db.append("easy!") assert(db.toString === "ScalaTest is easy!") } }
 "be fun" in { db => Future { db.append("fun!") assert(db.toString === "ScalaTest is fun!") } } }
 "Testing code" should { // This test doesn't need a Db "be clear" in { () => Future { val buf = new StringBuffer buf.append("ScalaTest code is ") buf.append("clear!") assert(buf.toString === "ScalaTest code is clear!") } } } }Often when you create fixtures in a trait like DbFixture, you'll still need to enable individual test classes to "setup" a newly created fixture before it gets passed into the tests. A good way to accomplish this is to pass the newly created fixture into a setup method, likepopulateDbin the previous example, before passing it to the test function. Classes that need to perform such setup can override the method, as doesExampleSuite.If a test doesn't need the fixture, you can indicate that by providing a no-arg instead of a one-arg function, as is done in the third test in the previous example, “ test code should be clear”. In other words, instead of starting your function literal with something like “db =>”, you'd start it with “() =>”. For such tests,runTestwill not invokewithFixture(OneArgAsyncTest). It will instead directly invokewithFixture(NoArgAsyncTest).Both examples shown above demonstrate the technique of giving each test its own "fixture sandbox" to play in. When your fixtures involve external side-effects, like creating files or databases, it is a good idea to give each file or database a unique name as is done in these examples. This keeps tests completely isolated, allowing you to run them in parallel if desired. You could mix ParallelTestExecutioninto either of theseExampleSuiteclasses, and the tests would run in parallel just fine.
- define the type of the fixture parameter by specifying type 
-    trait AsyncWordSpecLike extends AsyncTestSuite with AsyncTestRegistration with ShouldVerb with MustVerb with CanVerb with Informing with Notifying with Alerting with DocumentingImplementation trait for class fixture.AsyncWordSpec, which is a sister class toorg.scalatest.AsyncWordSpecthat can pass a fixture object into its tests.Implementation trait for class fixture.AsyncWordSpec, which is a sister class toorg.scalatest.AsyncWordSpecthat can pass a fixture object into its tests.fixture.AsyncWordSpecis a class, not a trait, to minimize compile time given there is a slight compiler overhead to mixing in traits compared to extending classes. If you need to mix the behavior offixture.AsyncWordSpecinto some other class, you can use this trait instead, because classfixture.AsyncWordSpecdoes nothing more than extend this trait and add a nicetoStringimplementation.See the documentation of the class for a detailed overview of fixture.AsyncWordSpec.
-    trait ConfigMapFixture extends AnyRefTrait that when mixed into a fixture.Suitepasses the config map passed torunTestas a fixture into each test.Trait that when mixed into a fixture.Suitepasses the config map passed torunTestas a fixture into each test.Here's an example in which tests just check to make sure "hello"and"world"are defined keys in the config map:package org.scalatest.examples.fixture.configmapfixture 
 import org.scalatest._
 class ExampleSpec extends fixture.FlatSpec with fixture.ConfigMapFixture with Matchers {
 "The config map" should "contain hello" in { configMap => // Use the configMap passed to runTest in the test configMap should contain key "hello" }
 it should "contain world" in { configMap => configMap should contain key "world" } }If you run this class without defining "hello"and"world"in the confg map, the tests will fail:scala> org.scalatest.run(new ExampleSpec) ExampleSpec: The config map - should contain hello *** FAILED *** Map() did not contain key "hello" ( :20) - should contain world *** FAILED *** Map() did not contain key "world" ( :24) If you do define "hello"and"world"keys in the confg map, the tests will success:scala> org.scalatest.run(new ExampleSpec, configMap = Map("hello" -> "hi", "world" -> "globe")) ExampleSpec: The config map - should contain hello - should contain world
-   abstract  class FeatureSpec extends FeatureSpecLikeA sister class to org.scalatest.FeatureSpecthat can pass a fixture object into its tests.A sister class to org.scalatest.FeatureSpecthat can pass a fixture object into its tests.Recommended Usage: Use class fixture.FeatureSpecin situations for whichFeatureSpecwould be a good choice, when all or most tests need the same fixture objects that must be cleaned up afterwards. Note:fixture.FeatureSpecis intended for use in special situations, with classFeatureSpecused for general needs. For more insight into wherefixture.FeatureSpecfits in the big picture, see thewithFixture(OneArgTest)subsection of the Shared fixtures section in the documentation for classFeatureSpec.Class fixture.FeatureSpecbehaves similarly to classorg.scalatest.FeatureSpec, except that tests may have a fixture parameter. The type of the fixture parameter is defined by the abstractFixtureParamtype, which is a member of this class. This trait also has an abstractwithFixturemethod. ThiswithFixturemethod takes aOneArgTest, which is a nested trait defined as a member of this class.OneArgTesthas anapplymethod that takes aFixtureParam. Thisapplymethod is responsible for running a test. This class'srunTestmethod delegates the actual running of each test towithFixture(OneArgTest), passing in the test code to run via theOneArgTestargument. ThewithFixture(OneArgTest)method (abstract in this class) is responsible for creating the fixture argument and passing it to the test function.Subclasses of this class must, therefore, do three things differently from a plain old org.scalatest.FeatureSpec:- define the type of the fixture parameter by specifying type FixtureParam
- define the withFixture(OneArgTest)method
- write tests that take a fixture parameter
- (You can also define tests that don't take a fixture parameter.)
 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 class. One good approach to passing multiple fixture objects is to encapsulate them in a case class. Here's an example: case class FixtureParam(file: File, writer: FileWriter) To enable the stacking of traits that define withFixture(NoArgTest), it is a good idea to letwithFixture(NoArgTest)invoke the test function instead of invoking the test function directly. To do so, you'll need to convert theOneArgTestto aNoArgTest. You can do that by passing the fixture object to thetoNoArgTestmethod ofOneArgTest. In other words, instead of writing “test(theFixture)”, you'd delegate responsibility for invoking the test function to thewithFixture(NoArgTest)method of the same instance by writing:withFixture(test.toNoArgTest(theFixture)) Here's a complete example: package org.scalatest.examples.featurespec.oneargtest 
 import org.scalatest.fixture import java.io._
 class ExampleSpec extends fixture.FeatureSpec {
 case class FixtureParam(file: File, writer: FileWriter)
 def withFixture(test: OneArgTest) = {
 // create the fixture val file = File.createTempFile("hello", "world") val writer = new FileWriter(file) val theFixture = FixtureParam(file, writer)
 try { writer.write("ScalaTest is designed to be ") // set up the fixture withFixture(test.toNoArgTest(theFixture)) // "loan" the fixture to the test } finally writer.close() // clean up the fixture }
 feature("Simplicity") { scenario("User needs to read test code written by others") { f => f.writer.write("encourage clear code!") f.writer.flush() assert(f.file.length === 49) }
 scenario("User needs to understand what the tests are doing") { f => f.writer.write("be easy to reason about!") f.writer.flush() assert(f.file.length === 52) } } }If a test fails, the OneArgTestfunction will result in a Failed wrapping the exception describing the failure. To ensure clean up happens even if a test fails, you should invoke the test function from inside atryblock and do the cleanup in afinallyclause, as shown in the previous example.Sharing fixtures across classesIf multiple test classes need the same fixture, you can define the FixtureParamandwithFixture(OneArgTest)implementations in a trait, then mix that trait into the test classes that need it. For example, if your application requires a database and your integration tests use that database, you will likely have many test classes that need a database fixture. You can create a "database fixture" trait that creates a database with a unique name, passes the connector into the test, then removes the database once the test completes. This is shown in the following example:package org.scalatest.examples.fixture.featurespec.sharing 
 import java.util.concurrent.ConcurrentHashMap import org.scalatest.fixture import DbServer._ import java.util.UUID.randomUUID
 object DbServer { // Simulating a database server type Db = StringBuffer private val databases = new ConcurrentHashMap[String, Db] def createDb(name: String): Db = { val db = new StringBuffer databases.put(name, db) db } def removeDb(name: String) { databases.remove(name) } }
 trait DbFixture { this: fixture.Suite =>
 type FixtureParam = Db
 // Allow clients to populate the database after // it is created def populateDb(db: Db) {}
 def withFixture(test: OneArgTest) { val dbName = randomUUID.toString val db = createDb(dbName) // create the fixture try { populateDb(db) // setup the fixture withFixture(test.toNoArgTest(db)) // "loan" the fixture to the test } finally removeDb(dbName) // clean up the fixture } }
 class ExampleSpec extends fixture.FeatureSpec with DbFixture {
 override def populateDb(db: Db) { // setup the fixture db.append("ScalaTest is designed to ") }
 feature("Simplicity") {
 scenario("User needs to read test code written by others") { db => db.append("encourage clear code!") assert(db.toString === "ScalaTest is designed to encourage clear code!") }
 scenario("User needs to understand what the tests are doing") { db => db.append("be easy to reason about!") assert(db.toString === "ScalaTest is designed to be easy to reason about!") }
 scenario("User needs to write tests") { () => val buf = new StringBuffer buf.append("ScalaTest is designed to be ") buf.append("easy to learn!") assert(buf.toString === "ScalaTest is designed to be easy to learn!") } } }Often when you create fixtures in a trait like DbFixture, you'll still need to enable individual test classes to "setup" a newly created fixture before it gets passed into the tests. A good way to accomplish this is to pass the newly created fixture into a setup method, likepopulateDbin the previous example, before passing it to the test function. Classes that need to perform such setup can override the method, as doesExampleSpec.If a test doesn't need the fixture, you can indicate that by providing a no-arg instead of a one-arg function, as is done in the third test in the previous example, “ Test code should be clear”. In other words, instead of starting your function literal with something like “db =>”, you'd start it with “() =>”. For such tests,runTestwill not invokewithFixture(OneArgTest). It will instead directly invokewithFixture(NoArgTest).Both examples shown above demonstrate the technique of giving each test its own "fixture sandbox" to play in. When your fixtures involve external side-effects, like creating files or databases, it is a good idea to give each file or database a unique name as is done in these examples. This keeps tests completely isolated, allowing you to run them in parallel if desired. You could mix ParallelTestExecutioninto either of theseExampleSpecclasses, and the tests would run in parallel just fine.
- define the type of the fixture parameter by specifying type 
-    trait FeatureSpecLike extends TestSuite with TestRegistration with Informing with Notifying with Alerting with DocumentingImplementation trait for class fixture.FeatureSpec, which is a sister class toorg.scalatest.FeatureSpecthat can pass a fixture object into its tests.Implementation trait for class fixture.FeatureSpec, which is a sister class toorg.scalatest.FeatureSpecthat can pass a fixture object into its tests.fixture.FeatureSpecis a class, not a trait, to minimize compile time given there is a slight compiler overhead to mixing in traits compared to extending classes. If you need to mix the behavior offixture.FeatureSpecinto some other class, you can use this trait instead, because classfixture.FeatureSpecdoes nothing more than extend this trait and add a nicetoStringimplementation.See the documentation of the class for a detailed overview of fixture.FeatureSpec.
-   abstract  class FlatSpec extends FlatSpecLikeA sister class to org.scalatest.FlatSpecthat can pass a fixture object into its tests.A sister class to org.scalatest.FlatSpecthat can pass a fixture object into its tests.Recommended Usage: Use class fixture.FlatSpecin situations for whichFlatSpecwould be a good choice, when all or most tests need the same fixture objects that must be cleaned up afterwards. Note:fixture.FlatSpecis intended for use in special situations, with classFlatSpecused for general needs. For more insight into wherefixture.FlatSpecfits in the big picture, see thewithFixture(OneArgTest)subsection of the Shared fixtures section in the documentation for classFlatSpec.Class fixture.FlatSpecbehaves similarly to classorg.scalatest.FlatSpec, except that tests may have a fixture parameter. The type of the fixture parameter is defined by the abstractFixtureParamtype, which is a member of this class. This class also contains an abstractwithFixturemethod. ThiswithFixturemethod takes aOneArgTest, which is a nested trait defined as a member of this class.OneArgTesthas anapplymethod that takes aFixtureParam. Thisapplymethod is responsible for running a test. This class'srunTestmethod delegates the actual running of each test towithFixture(OneArgTest), passing in the test code to run via theOneArgTestargument. ThewithFixture(OneArgTest)method (abstract in this class) is responsible for creating the fixture argument and passing it to the test function.Subclasses of this class must, therefore, do three things differently from a plain old org.scalatest.FlatSpec:- define the type of the fixture parameter by specifying type FixtureParam
- define the withFixture(OneArgTest)method
- write tests that take a fixture parameter
- (You can also define tests that don't take a fixture parameter.)
 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 class. One good approach to passing multiple fixture objects is to encapsulate them in a case class. Here's an example: case class FixtureParam(file: File, writer: FileWriter) To enable the stacking of traits that define withFixture(NoArgTest), it is a good idea to letwithFixture(NoArgTest)invoke the test function instead of invoking the test function directly. To do so, you'll need to convert theOneArgTestto aNoArgTest. You can do that by passing the fixture object to thetoNoArgTestmethod ofOneArgTest. In other words, instead of writing “test(theFixture)”, you'd delegate responsibility for invoking the test function to thewithFixture(NoArgTest)method of the same instance by writing:withFixture(test.toNoArgTest(theFixture)) Here's a complete example: package org.scalatest.examples.flatspec.oneargtest 
 import org.scalatest.fixture import java.io._
 class ExampleSpec extends fixture.FlatSpec {
 case class FixtureParam(file: File, writer: FileWriter)
 def withFixture(test: OneArgTest) = {
 // create the fixture val file = File.createTempFile("hello", "world") val writer = new FileWriter(file) val theFixture = FixtureParam(file, writer)
 try { writer.write("ScalaTest is ") // set up the fixture withFixture(test.toNoArgTest(theFixture)) // "loan" the fixture to the test } finally writer.close() // clean up the fixture }
 "Testing" should "be easy" in { f => f.writer.write("easy!") f.writer.flush() assert(f.file.length === 18) }
 it should "be fun" in { f => f.writer.write("fun!") f.writer.flush() assert(f.file.length === 17) } }If a test fails because of an exception, the OneArgTestfunction will result in a Failed wrapping the exception. To ensure clean up happens even if an exception occurs, you should invoke the test function from inside atryblock and do the cleanup in afinallyclause, as shown in the previous example.Sharing fixtures across classesIf multiple test classes need the same fixture, you can define the FixtureParamandwithFixture(OneArgTest)implementations in a trait, then mix that trait into the test classes that need it. For example, if your application requires a database and your integration tests use that database, you will likely have many test classes that need a database fixture. You can create a "database fixture" trait that creates a database with a unique name, passes the connector into the test, then removes the database once the test completes. This is shown in the following example:package org.scalatest.examples.fixture.flatspec.sharing 
 import java.util.concurrent.ConcurrentHashMap import org.scalatest.fixture import DbServer._ import java.util.UUID.randomUUID
 object DbServer { // Simulating a database server type Db = StringBuffer private val databases = new ConcurrentHashMap[String, Db] def createDb(name: String): Db = { val db = new StringBuffer databases.put(name, db) db } def removeDb(name: String) { databases.remove(name) } }
 trait DbFixture { this: fixture.Suite =>
 type FixtureParam = Db
 // Allow clients to populate the database after // it is created def populateDb(db: Db) {}
 def withFixture(test: OneArgTest) = { val dbName = randomUUID.toString val db = createDb(dbName) // create the fixture try { populateDb(db) // setup the fixture withFixture(test.toNoArgTest(db)) // "loan" the fixture to the test } finally removeDb(dbName) // clean up the fixture } }
 class ExampleSpec extends fixture.FlatSpec with DbFixture {
 override def populateDb(db: Db) { // setup the fixture db.append("ScalaTest is ") }
 "Testing" should "be easy" in { db => db.append("easy!") assert(db.toString === "ScalaTest is easy!") }
 it should "be fun" in { db => db.append("fun!") assert(db.toString === "ScalaTest is fun!") }
 // This test doesn't need a Db "Test code" should "be clear" in { () => val buf = new StringBuffer buf.append("ScalaTest code is ") buf.append("clear!") assert(buf.toString === "ScalaTest code is clear!") } }Often when you create fixtures in a trait like DbFixture, you'll still need to enable individual test classes to "setup" a newly created fixture before it gets passed into the tests. A good way to accomplish this is to pass the newly created fixture into a setup method, likepopulateDbin the previous example, before passing it to the test function. Classes that need to perform such setup can override the method, as doesExampleSpec.If a test doesn't need the fixture, you can indicate that by providing a no-arg instead of a one-arg function, as is done in the third test in the previous example, “ Test code should be clear”. In other words, instead of starting your function literal with something like “db =>”, you'd start it with “() =>”. For such tests,runTestwill not invokewithFixture(OneArgTest). It will instead directly invokewithFixture(NoArgTest).Both examples shown above demonstrate the technique of giving each test its own "fixture sandbox" to play in. When your fixtures involve external side-effects, like creating files or databases, it is a good idea to give each file or database a unique name as is done in these examples. This keeps tests completely isolated, allowing you to run them in parallel if desired. You could mix ParallelTestExecutioninto either of theseExampleSpecclasses, and the tests would run in parallel just fine.
- define the type of the fixture parameter by specifying type 
-    trait FlatSpecLike extends TestSuite with TestRegistration with ShouldVerb with MustVerb with CanVerb with Informing with Notifying with Alerting with DocumentingImplementation trait for class fixture.FlatSpec, which is a sister class toorg.scalatest.FlatSpecthat can pass a fixture object into its tests.Implementation trait for class fixture.FlatSpec, which is a sister class toorg.scalatest.FlatSpecthat can pass a fixture object into its tests.fixture.FlatSpecis a class, not a trait, to minimize compile time given there is a slight compiler overhead to mixing in traits compared to extending classes. If you need to mix the behavior offixture.FlatSpecinto some other class, you can use this trait instead, because classfixture.FlatSpecdoes nothing more than extend this trait and add a nicetoStringimplementation.See the documentation of the class for a detailed overview of fixture.FlatSpec.
-   abstract  class FreeSpec extends FreeSpecLikeA sister class to org.scalatest.FreeSpecthat can pass a fixture object into its tests.A sister class to org.scalatest.FreeSpecthat can pass a fixture object into its tests.Recommended Usage: Use class fixture.FreeSpecin situations for whichFreeSpecwould be a good choice, when all or most tests need the same fixture objects that must be cleaned up afterwards. Note:fixture.FreeSpecis intended for use in special situations, with classFreeSpecused for general needs. For more insight into wherefixture.FreeSpecfits in the big picture, see thewithFixture(OneArgTest)subsection of the Shared fixtures section in the documentation for classFreeSpec.Class fixture.FreeSpecbehaves similarly to classorg.scalatest.FreeSpec, except that tests may have a fixture parameter. The type of the fixture parameter is defined by the abstractFixtureParamtype, which is a member of this class. This class also has an abstractwithFixturemethod. ThiswithFixturemethod takes aOneArgTest, which is a nested trait defined as a member of this class.OneArgTesthas anapplymethod that takes aFixtureParam. Thisapplymethod is responsible for running a test. This class'srunTestmethod delegates the actual running of each test towithFixture(OneArgTest), passing in the test code to run via theOneArgTestargument. ThewithFixture(OneArgTest)method (abstract in this class) is responsible for creating the fixture argument and passing it to the test function.Subclasses of this class must, therefore, do three things differently from a plain old org.scalatest.FreeSpec:- define the type of the fixture parameter by specifying type FixtureParam
- define the withFixture(OneArgTest)method
- write tests that take a fixture parameter
- (You can also define tests that don't take a fixture parameter.)
 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 class. One good approach to passing multiple fixture objects is to encapsulate them in a case class. Here's an example: case class FixtureParam(file: File, writer: FileWriter) To enable the stacking of traits that define withFixture(NoArgTest), it is a good idea to letwithFixture(NoArgTest)invoke the test function instead of invoking the test function directly. To do so, you'll need to convert theOneArgTestto aNoArgTest. You can do that by passing the fixture object to thetoNoArgTestmethod ofOneArgTest. In other words, instead of writing “test(theFixture)”, you'd delegate responsibility for invoking the test function to thewithFixture(NoArgTest)method of the same instance by writing:withFixture(test.toNoArgTest(theFixture)) Here's a complete example: package org.scalatest.examples.freespec.oneargtest 
 import org.scalatest.fixture import java.io._
 class ExampleSpec extends fixture.FreeSpec {
 case class FixtureParam(file: File, writer: FileWriter)
 def withFixture(test: OneArgTest) = {
 // create the fixture val file = File.createTempFile("hello", "world") val writer = new FileWriter(file) val theFixture = FixtureParam(file, writer)
 try { writer.write("ScalaTest is ") // set up the fixture withFixture(test.toNoArgTest(theFixture)) // "loan" the fixture to the test } finally writer.close() // clean up the fixture }
 "Testing" - { "should be easy" in { f => f.writer.write("easy!") f.writer.flush() assert(f.file.length === 18) }
 "should be fun" in { f => f.writer.write("fun!") f.writer.flush() assert(f.file.length === 17) } } }If a test fails, the OneArgTestfunction will result in a Failed wrapping the exception describing the failure. To ensure clean up happens even if a test fails, you should invoke the test function from inside atryblock and do the cleanup in afinallyclause, as shown in the previous example.Sharing fixtures across classesIf multiple test classes need the same fixture, you can define the FixtureParamandwithFixture(OneArgTest)implementations in a trait, then mix that trait into the test classes that need it. For example, if your application requires a database and your integration tests use that database, you will likely have many test classes that need a database fixture. You can create a "database fixture" trait that creates a database with a unique name, passes the connector into the test, then removes the database once the test completes. This is shown in the following example:package org.scalatest.examples.fixture.freespec.sharing 
 import java.util.concurrent.ConcurrentHashMap import org.scalatest.fixture import DbServer._ import java.util.UUID.randomUUID
 object DbServer { // Simulating a database server type Db = StringBuffer private val databases = new ConcurrentHashMap[String, Db] def createDb(name: String): Db = { val db = new StringBuffer databases.put(name, db) db } def removeDb(name: String) { databases.remove(name) } }
 trait DbFixture { this: fixture.Suite =>
 type FixtureParam = Db
 // Allow clients to populate the database after // it is created def populateDb(db: Db) {}
 def withFixture(test: OneArgTest) = { val dbName = randomUUID.toString val db = createDb(dbName) // create the fixture try { populateDb(db) // setup the fixture withFixture(test.toNoArgTest(db)) // "loan" the fixture to the test } finally removeDb(dbName) // clean up the fixture } }
 class ExampleSpec extends fixture.FreeSpec with DbFixture {
 override def populateDb(db: Db) { // setup the fixture db.append("ScalaTest is ") }
 "Testing" - { "should be easy" in { db => db.append("easy!") assert(db.toString === "ScalaTest is easy!") }
 "should be fun" in { db => db.append("fun!") assert(db.toString === "ScalaTest is fun!") } }
 // This test doesn't need a Db "Test code" - { "should be clear" in { () => val buf = new StringBuffer buf.append("ScalaTest code is ") buf.append("clear!") assert(buf.toString === "ScalaTest code is clear!") } } }Often when you create fixtures in a trait like DbFixture, you'll still need to enable individual test classes to "setup" a newly created fixture before it gets passed into the tests. A good way to accomplish this is to pass the newly created fixture into a setup method, likepopulateDbin the previous example, before passing it to the test function. Classes that need to perform such setup can override the method, as doesExampleSpec.If a test doesn't need the fixture, you can indicate that by providing a no-arg instead of a one-arg function, as is done in the third test in the previous example, “ Test code should be clear”. In other words, instead of starting your function literal with something like “db =>”, you'd start it with “() =>”. For such tests,runTestwill not invokewithFixture(OneArgTest). It will instead directly invokewithFixture(NoArgTest).Both examples shown above demonstrate the technique of giving each test its own "fixture sandbox" to play in. When your fixtures involve external side-effects, like creating files or databases, it is a good idea to give each file or database a unique name as is done in these examples. This keeps tests completely isolated, allowing you to run them in parallel if desired. You could mix ParallelTestExecutioninto either of theseExampleSpecclasses, and the tests would run in parallel just fine.
- define the type of the fixture parameter by specifying type 
-    trait FreeSpecLike extends TestSuite with TestRegistration with Informing with Notifying with Alerting with DocumentingImplementation trait for class fixture.FreeSpec, which is a sister class toorg.scalatest.FreeSpecthat can pass a fixture object into its tests.Implementation trait for class fixture.FreeSpec, which is a sister class toorg.scalatest.FreeSpecthat can pass a fixture object into its tests.fixture.FreeSpecis a class, not a trait, to minimize compile time given there is a slight compiler overhead to mixing in traits compared to extending classes. If you need to mix the behavior offixture.FreeSpecinto some other class, you can use this trait instead, because classfixture.FreeSpecdoes nothing more than extend this trait and add a nicetoStringimplementation.See the documentation of the class for a detailed overview of fixture.FreeSpec.
-   abstract  class FunSpec extends FunSpecLikeA sister class to org.scalatest.FunSpecthat can pass a fixture object into its tests.A sister class to org.scalatest.FunSpecthat can pass a fixture object into its tests.Recommended Usage: Use class fixture.FunSpecin situations for whichFunSpecwould be a good choice, when all or most tests need the same fixture objects that must be cleaned up afterwards. Note:fixture.FunSpecis intended for use in special situations, with classFunSpecused for general needs. For more insight into wherefixture.FunSpecfits in the big picture, see thewithFixture(OneArgTest)subsection of the Shared fixtures section in the documentation for classFunSpec.Class fixture.FunSpecbehaves similarly to classorg.scalatest.FunSpec, except that tests may have a fixture parameter. The type of the fixture parameter is defined by the abstractFixtureParamtype, which is a member of this class. This class also contains an abstractwithFixturemethod. ThiswithFixturemethod takes aOneArgTest, which is a nested trait defined as a member of this class.OneArgTesthas anapplymethod that takes aFixtureParam. Thisapplymethod is responsible for running a test. This class'srunTestmethod delegates the actual running of each test towithFixture(OneArgTest), passing in the test code to run via theOneArgTestargument. ThewithFixture(OneArgTest)method (abstract in this class) is responsible for creating the fixture argument and passing it to the test function.Subclasses of this class must, therefore, do three things differently from a plain old org.scalatest.FunSpec:- define the type of the fixture parameter by specifying type FixtureParam
- define the withFixture(OneArgTest)method
- write tests that take a fixture parameter
- (You can also define tests that don't take a fixture parameter.)
 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 class. One good approach to passing multiple fixture objects is to encapsulate them in a case class. Here's an example: case class FixtureParam(file: File, writer: FileWriter) To enable the stacking of traits that define withFixture(NoArgTest), it is a good idea to letwithFixture(NoArgTest)invoke the test function instead of invoking the test function directly. To do so, you'll need to convert theOneArgTestto aNoArgTest. You can do that by passing the fixture object to thetoNoArgTestmethod ofOneArgTest. In other words, instead of writing “test(theFixture)”, you'd delegate responsibility for invoking the test function to thewithFixture(NoArgTest)method of the same instance by writing:withFixture(test.toNoArgTest(theFixture)) Here's a complete example: package org.scalatest.examples.funspec.oneargtest 
 import org.scalatest.fixture import java.io._
 class ExampleSpec extends fixture.FunSpec {
 case class FixtureParam(file: File, writer: FileWriter)
 def withFixture(test: OneArgTest) = {
 // create the fixture val file = File.createTempFile("hello", "world") val writer = new FileWriter(file) val theFixture = FixtureParam(file, writer)
 try { writer.write("ScalaTest is ") // set up the fixture withFixture(test.toNoArgTest(theFixture)) // "loan" the fixture to the test } finally writer.close() // clean up the fixture }
 describe("Testing") { it("should be easy") { f => f.writer.write("easy!") f.writer.flush() assert(f.file.length === 18) }
 it("should be fun") { f => f.writer.write("fun!") f.writer.flush() assert(f.file.length === 17) } } }If a test fails, the OneArgTestfunction will result in a Failed wrapping the exception describing the failure. To ensure clean up happens even if a test fails, you should invoke the test function from inside atryblock and do the cleanup in afinallyclause, as shown in the previous example.Sharing fixtures across classesIf multiple test classes need the same fixture, you can define the FixtureParamandwithFixture(OneArgTest)implementations in a trait, then mix that trait into the test classes that need it. For example, if your application requires a database and your integration tests use that database, you will likely have many test classes that need a database fixture. You can create a "database fixture" trait that creates a database with a unique name, passes the connector into the test, then removes the database once the test completes. This is shown in the following example:package org.scalatest.examples.fixture.funspec.sharing 
 import java.util.concurrent.ConcurrentHashMap import org.scalatest.fixture import DbServer._ import java.util.UUID.randomUUID
 object DbServer { // Simulating a database server type Db = StringBuffer private val databases = new ConcurrentHashMap[String, Db] def createDb(name: String): Db = { val db = new StringBuffer databases.put(name, db) db } def removeDb(name: String) { databases.remove(name) } }
 trait DbFixture { this: fixture.Suite =>
 type FixtureParam = Db
 // Allow clients to populate the database after // it is created def populateDb(db: Db) {}
 def withFixture(test: OneArgTest) = { val dbName = randomUUID.toString val db = createDb(dbName) // create the fixture try { populateDb(db) // setup the fixture withFixture(test.toNoArgTest(db)) // "loan" the fixture to the test } finally removeDb(dbName) // clean up the fixture } }
 class ExampleSpec extends fixture.FunSpec with DbFixture {
 override def populateDb(db: Db) { // setup the fixture db.append("ScalaTest is ") }
 describe("Testing") { it("should be easy") { db => db.append("easy!") assert(db.toString === "ScalaTest is easy!") }
 it("should be fun") { db => db.append("fun!") assert(db.toString === "ScalaTest is fun!") } }
 // This test doesn't need a Db describe("Test code") { it("should be clear") { () => val buf = new StringBuffer buf.append("ScalaTest code is ") buf.append("clear!") assert(buf.toString === "ScalaTest code is clear!") } } }Often when you create fixtures in a trait like DbFixture, you'll still need to enable individual test classes to "setup" a newly created fixture before it gets passed into the tests. A good way to accomplish this is to pass the newly created fixture into a setup method, likepopulateDbin the previous example, before passing it to the test function. Classes that need to perform such setup can override the method, as doesExampleSpec.If a test doesn't need the fixture, you can indicate that by providing a no-arg instead of a one-arg function, as is done in the third test in the previous example, “ Test code should be clear”. In other words, instead of starting your function literal with something like “db =>”, you'd start it with “() =>”. For such tests,runTestwill not invokewithFixture(OneArgTest). It will instead directly invokewithFixture(NoArgTest).Both examples shown above demonstrate the technique of giving each test its own "fixture sandbox" to play in. When your fixtures involve external side-effects, like creating files or databases, it is a good idea to give each file or database a unique name as is done in these examples. This keeps tests completely isolated, allowing you to run them in parallel if desired. You could mix ParallelTestExecutioninto either of theseExampleSpecclasses, and the tests would run in parallel just fine.
- define the type of the fixture parameter by specifying type 
-    trait FunSpecLike extends TestSuite with TestRegistration with Informing with Notifying with Alerting with DocumentingImplementation trait for class fixture.FunSpec, which is a sister class toorg.scalatest.FunSpecthat can pass a fixture object into its tests.Implementation trait for class fixture.FunSpec, which is a sister class toorg.scalatest.FunSpecthat can pass a fixture object into its tests.fixture.FunSpecis a class, not a trait, to minimize compile time given there is a slight compiler overhead to mixing in traits compared to extending classes. If you need to mix the behavior offixture.FunSpecinto some other class, you can use this trait instead, because classfixture.FunSpecdoes nothing more than extend this trait and add a nicetoStringimplementation.See the documentation of the class for a detailed overview of fixture.FunSpec.
-   abstract  class FunSuite extends FunSuiteLikeA sister class to org.scalatest.FunSuitethat can pass a fixture object into its tests.A sister class to org.scalatest.FunSuitethat can pass a fixture object into its tests.Recommended Usage: Use class fixture.FunSuitein situations for whichFunSuitewould be a good choice, when all or most tests need the same fixture objects that must be cleaned up afterwards. Note:fixture.FunSuiteis intended for use in special situations, with classFunSuiteused for general needs. For more insight into wherefixture.FunSuitefits in the big picture, see thewithFixture(OneArgTest)subsection of the Shared fixtures section in the documentation for classFunSuite.Class fixture.FunSuitebehaves similarly to classorg.scalatest.FunSuite, except that tests may have a fixture parameter. The type of the fixture parameter is defined by the abstractFixtureParamtype, which is a member of this class. This class also contains an abstractwithFixturemethod. ThiswithFixturemethod takes aOneArgTest, which is a nested trait defined as a member of this class.OneArgTesthas anapplymethod that takes aFixtureParam. Thisapplymethod is responsible for running a test. This class'srunTestmethod delegates the actual running of each test towithFixture(OneArgTest), passing in the test code to run via theOneArgTestargument. ThewithFixture(OneArgTest)method (abstract in this class) is responsible for creating the fixture argument and passing it to the test function.Subclasses of this class must, therefore, do three things differently from a plain old org.scalatest.FunSuite:- define the type of the fixture parameter by specifying type FixtureParam
- define the withFixture(OneArgTest)method
- write tests that take a fixture parameter
- (You can also define tests that don't take a fixture parameter.)
 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 class. One good approach to passing multiple fixture objects is to encapsulate them in a case class. Here's an example: case class FixtureParam(file: File, writer: FileWriter) To enable the stacking of traits that define withFixture(NoArgTest), it is a good idea to letwithFixture(NoArgTest)invoke the test function instead of invoking the test function directly. To do so, you'll need to convert theOneArgTestto aNoArgTest. You can do that by passing the fixture object to thetoNoArgTestmethod ofOneArgTest. In other words, instead of writing “test(theFixture)”, you'd delegate responsibility for invoking the test function to thewithFixture(NoArgTest)method of the same instance by writing:withFixture(test.toNoArgTest(theFixture)) Here's a complete example: package org.scalatest.examples.funsuite.oneargtest 
 import org.scalatest.fixture import java.io._
 class ExampleSuite extends fixture.FunSuite {
 case class FixtureParam(file: File, writer: FileWriter)
 def withFixture(test: OneArgTest) = {
 // create the fixture val file = File.createTempFile("hello", "world") val writer = new FileWriter(file) val theFixture = FixtureParam(file, writer)
 try { writer.write("ScalaTest is ") // set up the fixture withFixture(test.toNoArgTest(theFixture)) // "loan" the fixture to the test } finally writer.close() // clean up the fixture }
 test("testing should be easy") { f => f.writer.write("easy!") f.writer.flush() assert(f.file.length === 18) }
 test("testing should be fun") { f => f.writer.write("fun!") f.writer.flush() assert(f.file.length === 17) } }If a test fails, the OneArgTestfunction will result in a Failed wrapping the exception describing the failure. To ensure clean up happens even if a test fails, you should invoke the test function from inside atryblock and do the cleanup in afinallyclause, as shown in the previous example.Sharing fixtures across classesIf multiple test classes need the same fixture, you can define the FixtureParamandwithFixture(OneArgTest)implementations in a trait, then mix that trait into the test classes that need it. For example, if your application requires a database and your integration tests use that database, you will likely have many test classes that need a database fixture. You can create a "database fixture" trait that creates a database with a unique name, passes the connector into the test, then removes the database once the test completes. This is shown in the following example:package org.scalatest.examples.fixture.funsuite.sharing 
 import java.util.concurrent.ConcurrentHashMap import org.scalatest.fixture import DbServer._ import java.util.UUID.randomUUID
 object DbServer { // Simulating a database server type Db = StringBuffer private val databases = new ConcurrentHashMap[String, Db] def createDb(name: String): Db = { val db = new StringBuffer databases.put(name, db) db } def removeDb(name: String) { databases.remove(name) } }
 trait DbFixture { this: fixture.Suite =>
 type FixtureParam = Db
 // Allow clients to populate the database after // it is created def populateDb(db: Db) {}
 def withFixture(test: OneArgTest) = { val dbName = randomUUID.toString val db = createDb(dbName) // create the fixture try { populateDb(db) // setup the fixture withFixture(test.toNoArgTest(db)) // "loan" the fixture to the test } finally removeDb(dbName) // clean up the fixture } }
 class ExampleSuite extends fixture.FunSuite with DbFixture {
 override def populateDb(db: Db) { // setup the fixture db.append("ScalaTest is ") }
 test("testing should be easy") { db => db.append("easy!") assert(db.toString === "ScalaTest is easy!") }
 test("testing should be fun") { db => db.append("fun!") assert(db.toString === "ScalaTest is fun!") }
 // This test doesn't need a Db test("test code should be clear") { () => val buf = new StringBuffer buf.append("ScalaTest code is ") buf.append("clear!") assert(buf.toString === "ScalaTest code is clear!") } }Often when you create fixtures in a trait like DbFixture, you'll still need to enable individual test classes to "setup" a newly created fixture before it gets passed into the tests. A good way to accomplish this is to pass the newly created fixture into a setup method, likepopulateDbin the previous example, before passing it to the test function. Classes that need to perform such setup can override the method, as doesExampleSuite.If a test doesn't need the fixture, you can indicate that by providing a no-arg instead of a one-arg function, as is done in the third test in the previous example, “ test code should be clear”. In other words, instead of starting your function literal with something like “db =>”, you'd start it with “() =>”. For such tests,runTestwill not invokewithFixture(OneArgTest). It will instead directly invokewithFixture(NoArgTest).Both examples shown above demonstrate the technique of giving each test its own "fixture sandbox" to play in. When your fixtures involve external side-effects, like creating files or databases, it is a good idea to give each file or database a unique name as is done in these examples. This keeps tests completely isolated, allowing you to run them in parallel if desired. You could mix ParallelTestExecutioninto either of theseExampleSuiteclasses, and the tests would run in parallel just fine.
- define the type of the fixture parameter by specifying type 
-    trait FunSuiteLike extends TestSuite with TestRegistration with Informing with Notifying with Alerting with DocumentingImplementation trait for class fixture.FunSuite, which is a sister class toorg.scalatest.FunSuitethat can pass a fixture object into its tests.Implementation trait for class fixture.FunSuite, which is a sister class toorg.scalatest.FunSuitethat can pass a fixture object into its tests.fixture.FunSuiteis a class, not a trait, to minimize compile time given there is a slight compiler overhead to mixing in traits compared to extending classes. If you need to mix the behavior offixture.FunSuiteinto some other class, you can use this trait instead, because classfixture.FunSuitedoes nothing more than extend this trait and add a nicetoStringimplementation.See the documentation of the class for a detailed overview of fixture.FunSuite.
-    trait NoArg extends DelayedInit with () => UnitA function that takes no parameters (i.e., a Function0or "no-arg" function) and results inUnit, which when invoked executes the body of the constructor of the class into which this trait is mixed.A function that takes no parameters (i.e., a Function0or "no-arg" function) and results inUnit, which when invoked executes the body of the constructor of the class into which this trait is mixed.This trait extends DelayedInitand defines adelayedInitmethod that saves the body of the constructor (passed todelayedInit) for later execution whenapplyis invoked.This trait is somewhat magical and therefore may be challenging for your collegues to understand, so please use it as a last resort only when the simpler options described in the "shared fixtures" section of your chosen style trait won't do the job. NoArgis intended to address a specific use case that will likely be rare, and is unlikely to be useful outside of its intended use case, but it is quite handy for its intended use case (described in the next paragraph). One potential gotcha, for example, is that a subclass's constructor body could in theory be executed multiple times by simply invokingapplymultiple times. In the intended use case for this trait, however, the body will be executed only once.The intended use case for this method is (relatively rare) situations in which you want to extend a different instance of the same class for each test, with the body of the test inheriting the members of that class, and with code executed before and/or after the body of the test. For example, Akka's TestKitclass takes anActorSystem, which must have a unique name. To run a suite of tests in parallel, each test must get its ownActorSystem, to ensure the tests run in isolation. At the end of each test, theActorSystemmust be shutdown. WithNoArg, you can achieve this by first defining a class that extendsTestKitand mixes inNoArg. Here's an example taken with permission from the book Akka Concurrency, by Derek Wyatt:import akka.actor.ActorSystem import akka.testkit.{TestKit, ImplicitSender} import java.util.concurrent.atomic.AtomicInteger import org.scalatest.fixture.NoArg 
 object ActorSys { val uniqueId = new AtomicInteger(0) }
 class ActorSys(name: String) extends TestKit(ActorSystem(name)) with ImplicitSender with NoArg {
 def this() = this( "TestSystem%05d".format( ActorSys.uniqueId.getAndIncrement()))
 def shutdown(): Unit = system.shutdown()
 override def apply() { try super.apply() finally shutdown() } }Given this implementation of ActorSys, which will invokeshutdownafter the constructor code is executed, you can run each test in a suite in a subclass ofTestKit, giving each test'sTestKitanActorSystemwith a unique name, allowing you to safely run those tests in parallel. Here's an example from Akka Concurrency:class MyActorSpec extends fixture.WordSpec with Matchers with UnitFixture with ParallelTestExecution { 
 def makeActor(): ActorRef = system.actorOf(Props[MyActor], "MyActor")
 "My Actor" should { "throw when made with the wrong name" in new ActorSys { an [Exception] should be thrownBy { // use a generated name val a = system.actorOf(Props[MyActor]) } } "construct without exception" in new ActorSys { val a = makeActor() // The throw will cause the test to fail } "respond with a Pong to a Ping" in new ActorSys { val a = makeActor() a ! Ping expectMsg(Pong) } } }UnitFixtureis used in this example, because in this case, thefixture.WordSpecfeature enabling tests to be defined as functions from fixture objects of typeFixtureParamtoUnitis not being used. Rather, only the secondary feature that enables tests to be defined as functions from no parameters toUnitis being used. This secondary feature is described in the second-to-last paragraph on the main Scaladoc documentation offixture.WordSpec, which says:If a test doesn't need the fixture, you can indicate that by providing a no-arg instead of a one-arg function, ... In other words, instead of starting your function literal with something like “ db =>”, you'd start it with “() =>”. For such tests,runTestwill not invokewithFixture(OneArgTest). It will instead directly invokewithFixture(NoArgTest).Since FixtureParamis unused in this use case, it could be anything. Making itUnitwill hopefully help readers more easily recognize that it is not being used.Note: As of Scala 2.11, DelayedInit(which is used byNoArg) has been deprecated, to indicate it is buggy and should be avoided if possible. Those in charge of the Scala compiler and standard library have promised thatDelayedInitwill not be removed from Scala unless an alternate way to achieve the same goal is provided. Thus it should be safe to useNoArg, but if you'd rather not you can achieve the same effect with a bit more boilerplate by extending (() => Unit) instead ofNoArgand placing your code in an explicitbodymethod. Here's an example:import akka.actor.ActorSystem import akka.testkit.{TestKit, ImplicitSender} import java.util.concurrent.atomic.AtomicInteger import org.scalatest.fixture.NoArg 
 object ActorSys { val uniqueId = new AtomicInteger(0) }
 class ActorSys(name: String) extends TestKit(ActorSystem(name)) with ImplicitSender with (() => Unit) {
 def this() = this( "TestSystem%05d".format( ActorSys.uniqueId.getAndIncrement()))
 def shutdown(): Unit = system.shutdown() def body(): Unit
 override def apply() = { try body() finally shutdown() } }Using this version of ActorSyswill require an explicitbodymethod in the tests:class MyActorSpec extends fixture.WordSpec with Matchers with UnitFixture with ParallelTestExecution { 
 def makeActor(): ActorRef = system.actorOf(Props[MyActor], "MyActor")
 "My Actor" should { "throw when made with the wrong name" in new ActorSys { def body() = an [Exception] should be thrownBy { // use a generated name val a = system.actorOf(Props[MyActor]) } } "construct without exception" in new ActorSys { def body() = { val a = makeActor() // The throw will cause the test to fail } } "respond with a Pong to a Ping" in new ActorSys { def body() = { val a = makeActor() a ! Ping expectMsg(Pong) } } } }
-   abstract  class PropSpec extends PropSpecLikeA sister class to org.scalatest.PropSpecthat can pass a fixture object into its tests.A sister class to org.scalatest.PropSpecthat can pass a fixture object into its tests.Recommended Usage: Use class fixture.PropSpecin situations for whichPropSpecwould be a good choice, when all or most tests need the same fixture objects that must be cleaned up afterwards. Note:fixture.PropSpecis intended for use in special situations, with classPropSpecused for general needs. For more insight into wherefixture.PropSpecfits in the big picture, see thewithFixture(OneArgTest)subsection of the Shared fixtures section in the documentation for classPropSpec.Class fixture.PropSpecbehaves similarly to classorg.scalatest.PropSpec, except that tests may have a fixture parameter. The type of the fixture parameter is defined by the abstractFixtureParamtype, which is a member of this class. This class also has an abstractwithFixturemethod. ThiswithFixturemethod takes aOneArgTest, which is a nested trait defined as a member of this class.OneArgTesthas anapplymethod that takes aFixtureParam. Thisapplymethod is responsible for running a test. This class'srunTestmethod delegates the actual running of each test towithFixture, passing in the test code to run via theOneArgTestargument. ThewithFixturemethod (abstract in this class) is responsible for creating the fixture argument and passing it to the test function.Subclasses of this class must, therefore, do three things differently from a plain old org.scalatest.PropSpec:- define the type of the fixture parameter by specifying type FixtureParam
- define the withFixture(OneArgTest)method
- write tests that take a fixture parameter
- (You can also define tests that don't take a fixture parameter.)
 Here's an example: package org.scalatest.examples.fixture.propspec 
 import org.scalatest._ import prop.PropertyChecks import java.io._
 class ExampleSpec extends fixture.PropSpec with PropertyChecks with Matchers {
 // 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 property-based tests that take a fixture parameter // (Hopefully less contrived than the examples shown here.) property("can read from a temp file") { reader => var builder = new StringBuilder var c = reader.read() while (c != -1) { builder.append(c.toChar) c = reader.read() } val fileContents = builder.toString forAll { (c: Char) => whenever (c != 'H') { fileContents should not startWith c.toString } } }
 property("can read the first char of the temp file") { reader => val firstChar = reader.read() forAll { (c: Char) => whenever (c != 'H') { c should not equal firstChar } } }
 // (You can also write tests that don't take a fixture parameter.) property("can write tests that don't take the fixture") { () => forAll { (i: Int) => i + i should equal (2 * i) } } }Note: to run the examples on this page, you'll need to include ScalaCheck on the classpath in addition to ScalaTest. In the previous example, withFixturecreates and initializes a temp file, then invokes the test function, passing in aFileReaderconnected to that file. In addition to setting up the fixture before a test, thewithFixturemethod also cleans it up afterwards. If you need to do some clean up that must happen even if a test fails, you should invoke the test function from inside atryblock and do the cleanup in afinallyclause, as shown in the previous example.If a test fails, the OneArgTestfunction will result in a Failed wrapping the exception describing the failure. The reason you must perform cleanup in afinallyclause is that in case an exception propagates back throughwithFixture, thefinallyclause will ensure the fixture cleanup happens as that exception propagates back up the call stack torunTest.If a test doesn't need the fixture, you can indicate that by providing a no-arg instead of a one-arg function. In other words, instead of starting your function literal with something like “ reader =>”, you'd start it with “() =>”, as is done in the third test in the above example. For such tests,runTestwill not invokewithFixture(OneArgTest). It will instead directly invokewithFixture(NoArgTest).Passing multiple fixture objectsIf 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 class. One good approach to passing multiple fixture objects is to encapsulate them in a case class. Here's an example: case class FixtureParam(builder: StringBuilder, buffer: ListBuffer[String]) To enable the stacking of traits that define withFixture(NoArgTest), it is a good idea to letwithFixture(NoArgTest)invoke the test function instead of invoking the test function directly. To do so, you'll need to convert theOneArgTestto aNoArgTest. You can do that by passing the fixture object to thetoNoArgTestmethod ofOneArgTest. In other words, instead of writing “test(theFixture)”, you'd delegate responsibility for invoking the test function to thewithFixture(NoArgTest)method of the same instance by writing:withFixture(test.toNoArgTest(theFixture)) Here's a complete example: package org.scalatest.examples.fixture.propspec.multi 
 import org.scalatest._ import prop.PropertyChecks import scala.collection.mutable.ListBuffer
 class ExampleSpec extends fixture.PropSpec with PropertyChecks with Matchers {
 case class FixtureParam(builder: StringBuilder, buffer: ListBuffer[String])
 def withFixture(test: OneArgTest) = {
 // Create needed mutable objects val stringBuilder = new StringBuilder("ScalaTest is ") val listBuffer = new ListBuffer[String] val theFixture = FixtureParam(stringBuilder, listBuffer)
 // Invoke the test function, passing in the mutable objects withFixture(test.toNoArgTest(theFixture)) }
 property("testing should be easy") { f => f.builder.append("easy!") assert(f.builder.toString === "ScalaTest is easy!") assert(f.buffer.isEmpty) val firstChar = f.builder(0) forAll { (c: Char) => whenever (c != 'S') { c should not equal firstChar } } f.buffer += "sweet" }
 property("testing should be fun") { f => f.builder.append("fun!") assert(f.builder.toString === "ScalaTest is fun!") assert(f.buffer.isEmpty) val firstChar = f.builder(0) forAll { (c: Char) => whenever (c != 'S') { c should not equal firstChar } } } }
- define the type of the fixture parameter by specifying type 
-    trait PropSpecLike extends TestSuite with TestRegistration with Informing with Notifying with Alerting with DocumentingImplementation trait for class fixture.PropSpec, which is a sister class toorg.scalatest.PropSpecthat can pass a fixture object into its tests.Implementation trait for class fixture.PropSpec, which is a sister class toorg.scalatest.PropSpecthat can pass a fixture object into its tests.fixture.PropSpecis a class, not a trait, to minimize compile time given there is a slight compiler overhead to mixing in traits compared to extending classes. If you need to mix the behavior offixture.PropSpecinto some other class, you can use this trait instead, because classfixture.PropSpecdoes nothing more than extend this trait and add a nicetoStringimplementation.See the documentation of the class for a detailed overview of fixture.PropSpec.
-    trait Suite extends scalatest.SuiteBase trait for a family of style traits that can pass a fixture object into tests. 
-    trait TestDataFixture extends AnyRefTrait that when mixed into a fixture.Suitepasses theTestDatapassed towithFixtureas a fixture into each test.Trait that when mixed into a fixture.Suitepasses theTestDatapassed towithFixtureas a fixture into each test.For example, here's how you could access the test's name in each test using TestDataFixture:package org.scalatest.examples.fixture.testdatafixture 
 import org.scalatest._
 class ExampleSpec extends fixture.FlatSpec with fixture.TestDataFixture {
 "Accessing the test data" should "be easy!" in { td => assert(td.name == "Accessing the test data should be easy!") }
 it should "be fun!" in { td => assert(td.name == "Accessing the test data should be fun!") } }
-    trait TestRegistration extends AnyRefTrait declaring methods that can be used to register test functions that accept a fixture parameter and have any result type. 
-  trait TestSuite extends Suite with scalatest.TestSuite
-    trait UnitFixture extends AnyRefTrait that when mixed into a fixture.Suitepasses the unit value as a fixture into each test.Trait that when mixed into a fixture.Suitepasses the unit value as a fixture into each test.Since a unit value is unlikely to be of much use to a test, this trait is useful when the unit value fixture is actually never passed into any tests. Instead each test in the fixture.Suiteis defined as a no-arg function; no tests are defined as one-arg functions. This should be quite rare, but occasionally can be useful. For an example, see the main documentation for traitNoArg.
-   abstract  class WordSpec extends WordSpecLikeA sister class to org.scalatest.WordSpecthat can pass a fixture object into its tests.A sister class to org.scalatest.WordSpecthat can pass a fixture object into its tests.Recommended Usage: Use class fixture.WordSpecin situations for whichWordSpecwould be a good choice, when all or most tests need the same fixture objects that must be cleaned up afterwards. Note:fixture.WordSpecis intended for use in special situations, with classWordSpecused for general needs. For more insight into wherefixture.WordSpecfits in the big picture, see thewithFixture(OneArgTest)subsection of the Shared fixtures section in the documentation for classWordSpec.Class fixture.WordSpecbehaves similarly to classorg.scalatest.WordSpec, except that tests may have a fixture parameter. The type of the fixture parameter is defined by the abstractFixtureParamtype, which is a member of this class. This class also has an abstractwithFixturemethod. ThiswithFixturemethod takes aOneArgTest, which is a nested trait defined as a member of this class.OneArgTesthas anapplymethod that takes aFixtureParam. Thisapplymethod is responsible for running a test. This class'srunTestmethod delegates the actual running of each test towithFixture(OneArgTest), passing in the test code to run via theOneArgTestargument. ThewithFixture(OneArgTest)method (abstract in this class) is responsible for creating the fixture argument and passing it to the test function.Subclasses of this class must, therefore, do three things differently from a plain old org.scalatest.WordSpec:- define the type of the fixture parameter by specifying type FixtureParam
- define the withFixture(OneArgTest)method
- write tests that take a fixture parameter
- (You can also define tests that don't take a fixture parameter.)
 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 class. One good approach to passing multiple fixture objects is to encapsulate them in a case class. Here's an example: case class FixtureParam(file: File, writer: FileWriter) To enable the stacking of traits that define withFixture(NoArgTest), it is a good idea to letwithFixture(NoArgTest)invoke the test function instead of invoking the test function directly. To do so, you'll need to convert theOneArgTestto aNoArgTest. You can do that by passing the fixture object to thetoNoArgTestmethod ofOneArgTest. In other words, instead of writing “test(theFixture)”, you'd delegate responsibility for invoking the test function to thewithFixture(NoArgTest)method of the same instance by writing:withFixture(test.toNoArgTest(theFixture)) Here's a complete example: package org.scalatest.examples.wordspec.oneargtest 
 import org.scalatest.fixture import java.io._
 class ExampleSpec extends fixture.WordSpec {
 case class FixtureParam(file: File, writer: FileWriter)
 def withFixture(test: OneArgTest) = {
 // create the fixture val file = File.createTempFile("hello", "world") val writer = new FileWriter(file) val theFixture = FixtureParam(file, writer)
 try { writer.write("ScalaTest is ") // set up the fixture withFixture(test.toNoArgTest(theFixture)) // "loan" the fixture to the test } finally writer.close() // clean up the fixture }
 "Testing" should { "be easy" in { f => f.writer.write("easy!") f.writer.flush() assert(f.file.length === 18) }
 "be fun" in { f => f.writer.write("fun!") f.writer.flush() assert(f.file.length === 17) } } }If a test fails, the OneArgTestfunction will result in a Failed wrapping the exception describing the failure. To ensure clean up happens even if a test fails, you should invoke the test function from inside atryblock and do the cleanup in afinallyclause, as shown in the previous example.Sharing fixtures across classesIf multiple test classes need the same fixture, you can define the FixtureParamandwithFixture(OneArgTest)implementations in a trait, then mix that trait into the test classes that need it. For example, if your application requires a database and your integration tests use that database, you will likely have many test classes that need a database fixture. You can create a "database fixture" trait that creates a database with a unique name, passes the connector into the test, then removes the database once the test completes. This is shown in the following example:package org.scalatest.examples.fixture.wordspec.sharing 
 import java.util.concurrent.ConcurrentHashMap import org.scalatest.fixture import DbServer._ import java.util.UUID.randomUUID
 object DbServer { // Simulating a database server type Db = StringBuffer private val databases = new ConcurrentHashMap[String, Db] def createDb(name: String): Db = { val db = new StringBuffer databases.put(name, db) db } def removeDb(name: String) { databases.remove(name) } }
 trait DbFixture { this: fixture.Suite =>
 type FixtureParam = Db
 // Allow clients to populate the database after // it is created def populateDb(db: Db) {}
 def withFixture(test: OneArgTest) = { val dbName = randomUUID.toString val db = createDb(dbName) // create the fixture try { populateDb(db) // setup the fixture withFixture(test.toNoArgTest(db)) // "loan" the fixture to the test } finally removeDb(dbName) // clean up the fixture } }
 class ExampleSpec extends fixture.WordSpec with DbFixture {
 override def populateDb(db: Db) { // setup the fixture db.append("ScalaTest is ") }
 "Testing" should { "should be easy" in { db => db.append("easy!") assert(db.toString === "ScalaTest is easy!") }
 "should be fun" in { db => db.append("fun!") assert(db.toString === "ScalaTest is fun!") } }
 // This test doesn't need a Db "Test code" should { "should be clear" in { () => val buf = new StringBuffer buf.append("ScalaTest code is ") buf.append("clear!") assert(buf.toString === "ScalaTest code is clear!") } } }Often when you create fixtures in a trait like DbFixture, you'll still need to enable individual test classes to "setup" a newly created fixture before it gets passed into the tests. A good way to accomplish this is to pass the newly created fixture into a setup method, likepopulateDbin the previous example, before passing it to the test function. Classes that need to perform such setup can override the method, as doesExampleSpec.If a test doesn't need the fixture, you can indicate that by providing a no-arg instead of a one-arg function, as is done in the third test in the previous example, “ Test code should be clear”. In other words, instead of starting your function literal with something like “db =>”, you'd start it with “() =>”. For such tests,runTestwill not invokewithFixture(OneArgTest). It will instead directly invokewithFixture(NoArgTest).Both examples shown above demonstrate the technique of giving each test its own "fixture sandbox" to play in. When your fixtures involve external side-effects, like creating files or databases, it is a good idea to give each file or database a unique name as is done in these examples. This keeps tests completely isolated, allowing you to run them in parallel if desired. You could mix ParallelTestExecutioninto either of theseExampleSpecclasses, and the tests would run in parallel just fine.
- define the type of the fixture parameter by specifying type 
-    trait WordSpecLike extends TestSuite with TestRegistration with ShouldVerb with MustVerb with CanVerb with Informing with Notifying with Alerting with DocumentingImplementation trait for class fixture.WordSpec, which is a sister class toorg.scalatest.WordSpecthat can pass a fixture object into its tests.Implementation trait for class fixture.WordSpec, which is a sister class toorg.scalatest.WordSpecthat can pass a fixture object into its tests.fixture.WordSpecis a class, not a trait, to minimize compile time given there is a slight compiler overhead to mixing in traits compared to extending classes. If you need to mix the behavior offixture.WordSpecinto some other class, you can use this trait instead, because classfixture.WordSpecdoes nothing more than extend this trait and add a nicetoStringimplementation.See the documentation of the class for a detailed overview of fixture.WordSpec.
Deprecated Type Members
-   abstract  class Spec extends SpecLikeClass fixture.Spechas been deprecated and will be removed in a future version of ScalaTest. Please useorg.scalatest.fixture.FunSpecinstead.Class fixture.Spechas been deprecated and will be removed in a future version of ScalaTest. Please useorg.scalatest.fixture.FunSpecinstead.Because this style uses reflection at runtime to discover scopes and tests, it can only be supported on the JVM, not Scala.js. Thus in ScalaTest 3.0.0, class org.scalatest.Specwas moved to theorg.scalatest.refspecpackage and renamedRefSpec, with the intention of later moving it to a separate module available only on the JVM. If theorg.scalatest.refspec._package contained afixturesubpackage, then importingorg.scalatest.refspec._would import the namefixtureasorg.scalatest.refspec.fixture. This would likely be confusing for users, who expectfixtureto meanorg.scalatest.fixture.As a result this class has been deprecated and will not be moved to package org.scalatest.refspec. Instead we recommend you rewrite any test classes that currently extendorg.scalatest.fixture.Specto extendorg.scalatest.fixture.FunSpecinstead, replacing any scopeobjectwith adescribeclause, and any test method with anitclause.- Annotations
- @deprecated
- Deprecated
- fixture.Spec has been deprecated and will be removed in a future version of ScalaTest. Please use org.scalatest.fixture.FunSpec instead. 
 
-    trait SpecLike extends TestSuite with Informing with Notifying with Alerting with DocumentingTrait fixture.SpecLikehas been deprecated and will be removed in a future version of ScalaTest. Please useorg.scalatest.fixture.FunSpecinstead.Trait fixture.SpecLikehas been deprecated and will be removed in a future version of ScalaTest. Please useorg.scalatest.fixture.FunSpecinstead.Because this style uses reflection at runtime to discover scopes and tests, it can only be supported on the JVM, not Scala.js. Thus in ScalaTest 3.0.0, class org.scalatest.SpecLikewas moved to theorg.scalatest.refspecpackage and renamedRefSpecLike, with the intention of later moving it to a separate module available only on the JVM. If theorg.scalatest.refspec._package contained afixturesubpackage, then importingorg.scalatest.refspec._would import the namefixtureasorg.scalatest.refspec.fixture. This would likely be confusing for users, who expectfixtureto meanorg.scalatest.fixture.As a result this class has been deprecated and will not be moved to package org.scalatest.refspec. Instead we recommend you rewrite any test classes that currently extendorg.scalatest.fixture.SpecLiketo extendorg.scalatest.fixture.FunSpecLikeinstead, replacing any scopeobjectwith adescribeclause, and any test method with anitclause.- Annotations
- @deprecated
- Deprecated
- fixture.SpecLike has been deprecated and will be removed in a future version of ScalaTest. Please use org.scalatest.fixture.FunSpecLike instead.