|
ScalaTest 0.9.2
|
|
org/scalatest/Suite.scala]
trait
Suite
extends AnyRef
A suite of tests. A Suite instance encapsulates a conceptual
suite (i.e., a collection) of tests. This trait defines a default way to create
and execute tests, which involves writing test methods. This approach will likely suffice
in the vast majority of applications, but if desired, subtypes can override certain methods
to define other ways to create and execute tests.
The easiest way to use this trait is to use its default approach: Simply create classes that
extend Suite and define test methods. Test methods have names of the form testX,
where X is some unique, hopefully meaningful, string. A test method must be public and
can have any result type, but the most common result type is Unit. Here's an example:
import org.scalatest.Suite
class MySuite extends Suite {
def testAddition() {
val sum = 1 + 1
assert(sum === 2)
assert(sum + 2 === 4)
}
def testSubtraction() {
val diff = 4 - 1
assert(diff === 3)
assert(diff - 2 === 1)
}
}
You run a Suite by invoking on it one of three overloaded execute
methods. Two of these execute methods are intended to serve as a
convenient way to run tests from within the Scala interpreter. For example,
to run MySuite from within the Scala interpreter, you could write:
scala> (new MySuite).execute()
Or, to run just the testAddition method, you could write:
scala> (new MySuite).execute("testAddition")
These two execute methods print test results to the standard output. If you try these two examples
from within the Scala interpeter, you should see reports that indicate the tests were started and successfully completed.
The third overloaded execute method takes seven parameters, so it is a bit unwieldy to invoke from
within the Scala interpreter. Instead, this execute method is intended to be invoked indirectly by a test runner, such
as Runner or an IDE. See the documentation for Runner for more detail.
Assertions and ===
Inside test methods, you can write assertions by invoking assert and passing in a Boolean expression,
such as:
val left = 2 val right = 1 assert(left == right)
If the passed expression is true, assert will return normally. If false,
assert will complete abruptly with an AssertionError. This exception is usually not caught
by the test method, which means the test method itself will complete abruptly by throwing the AssertionError. Any
test method that completes abruptly with an AssertionError or any Exception is considered a failed
test. A test method that returns normally is considered a successful test.
If you pass a Boolean expression to assert, a failed assertion will be reported, but without
reporting the left and right values. You can alternatively encode these values in a String passed as
a second argument to assert, as in:
val left = 2 val right = 1 assert(left == right, left + " did not equal " + right)
Using this form of assert, the failure report will include the left and right values, thereby
helping you debug the problem. However, Suite provides the === operator to make this easier.
You use it like this:
val left = 2 val right = 1 assert(left === right)
Because you use === here instead of ==, the failure report will include the left
and right values. For example, the detail message in the thrown AssertionErrorm from the assert
shown previously will include, "2 did not equal 1".
From this message you will know that the operand on the left had the value 2, and the operand on the right had the value 1.
If you're familiar with JUnit, you would use ===
in a ScalaTest Suite where you'd use assertEquals in a JUnit TestCase.
The === operator is made possible by an implicit conversion from Any
to Equalizer. If you're curious to understand the mechanics, see the documentation for
Equalizer and Suite's convertToEqualizer method.
Expected results
Although=== provides a natural, readable extension to Scala's assert mechanism,
as the operands become lengthy, the code becomes less readable. In addition, the === comparison
doesn't distinguish between actual and expected values. The operands are just called left and right,
because if one were named expected and the other actual, it would be difficult for people to
remember which was which. To help with these limitations of assertions, Suite includes a method called expect that
can be used as an alternative to assert with ===. To use expect, you place
the expected value in parentheses after expect, and follow that by code contained inside
curly braces that results in a value that you expect should equal the expected value. For example:
val a = 5
val b = 2
expect(2) {
a - b
}
In this case, the expected value is 2, and the code being tested is a - b. This expectation will fail, and
the detail message in the AssertionError will read, "Expected 2, but got 3."
Intercepted exceptions
Sometimes you need to test whether a method throws an expected exception under certain circumstances, such as when invalid arguments are passed to the method. You can do this in the JUnit style, like this:
val s = "hi"
try {
s.charAt(-1)
fail()
}
catch {
case e: IndexOutOfBoundsException => // Expected, so continue
}
If charAt throws IndexOutOfBoundsException as left, control will transfer
to the catch case, which does nothing. If, however, charAt fails to throw an exception,
the next statement, fail(), will be executed. The fail method always completes abruptly with
an AssertionError, thereby signaling a failed test.
To make this common use case easier to express and read, Suite provides an intercept
method. You use it like this:
val s = "hi"
intercept(classOf[IndexOutOfBoundsException]) {
s.charAt(-1)
}
This code behaves much like the previous example. If charAt throws an instance of IndexOutOfBoundsException,
intercept will return that exception. But if charAt completes normally, or throws a different
exception, intercept will complete abruptly with an AssertionError. intercept returns the
caught exception so that you can inspect it further if you wish, for example, to ensure that data contained inside
the exception has the expected values.
Nested suites
A Suite can refer to a collection of other Suites,
which are called nested Suites. Those nested Suites can in turn have
their own nested Suites, and so on. Large test suites can be organized, therefore, as a tree of
nested Suites.
This trait's execute method, in addition to invoking its
test methods, invokes execute on each of its nested Suites.
A List of a Suite's nested Suites can be obtained by invoking its
nestedSuites method. If you wish to create a Suite that serves as a
container for nested Suites, whether or not it has test methods of its own, simply override nestedSuites
to return a List of the nested Suites. Because this is a common use case, ScalaTest provides
a convenience SuperSuite class, which takes a List of nested Suites as a constructor
parameter. Here's an example:
import org.scalatet.Suite
class ASuite extends Suite
class BSuite extends Suite
class CSuite extends Suite
class AlphabetSuite extends SuperSuite(
List(
new ASuite,
new BSuite,
new CSuite
)
)
If you now run AlphabetSuite, for example from the interpreter:
scala> (new AlphabetSuite).execute()
You will see reports printed to the standard output that indicate nested
suites—ASuite, BSuite, and
CSuite—were run.
Note that Runner can discover Suites automatically, so you need not
necessarily specify SuperSuites explicitly. See the documentation
for Runner for more information.
Test fixtures
A test fixture is objects or other artifacts (such as files, sockets, database
connections, etc.) used by tests to do their work.
If a fixture is used by only one test method, then the definitions of the fixture objects should
be local to the method, such as the objects assigned to sum and diff of the
earlier MySuite examples. If multiple methods need to share a fixture, the best approach
is to assign them to instance variables. Here's a (very contrived) example, in which the object assigned
to shared is used by multiple test methods:
import org.scalatest.Suite
class MySuite extends Suite {
// Sharing fixture objects via instance variables
val shared = 5
def testAddition() {
val sum = 2 + 3
assert(sum === shared)
}
def testSubtraction() {
val diff = 7 - 2
assert(diff === shared)
}
}
In some cases, however, a shared fixture may be changed by a test method such that
it needs to be recreated or reinitialized before each test. It may also need to
be cleaned up after each test. JUnit offers methods setup and
tearDown for this purpose. In ScalaTest, you can avoid
vars by writing a createFixture method
that returns a new instance of the fixture object (or returns a tuple of new instances of
fixture objects) each time it is called. You can then call createFixture at the beginning of each
test method that needs the fixture, storing the fixture object or objects in local variables. Here's an example:
import org.scalatest._
import scala.collection.mutable.ListBuffer
class MySuite extends Suite {
def createFixture = (new StringBuilder("ScalaTest is "), new ListBuffer[String])
def testEasy() {
val (sb, lb) = createFixture
sb.append("easy!")
assert(sb.toString === "ScalaTest is easy!")
assert(lb.isEmpty)
lb += "sweet"
}
def testFun() {
val (sb, lb) = createFixture
sb.append("fun!")
assert(sb.toString === "ScalaTest is fun!")
assert(lb.isEmpty)
}
}
Another approach to fixtures that avoids vars is to use traits FunSuite1 through FunSuite9.
If you prefer instead to reassign variables to reinitialize a fixture, however, one approach is to override runTest.
Here's an example:
import org.scalatest._
class MySuite extends Suite {
var sb: StringBuilder = _
override protected def runTest(testName: String, reporter: Reporter,
stopper: Stopper, properties: Map[String, Any]) {
// First, initialize the fixture. This
// would be in JUnit's setup() method.
sb = new StringBuilder("ScalaTest is ")
// Then call super.runTest to run the test
super.runTest(testName, reporter, stopper, properties)
// Then perform cleanup. This would be in
// JUnit's teardown() method. If needed, you could
// also do cleanup in a finally clause.
sb.setLength(0)
}
def testEasy() {
sb.append("easy!")
assert(sb.toString === "ScalaTest is easy!")
}
def testFun() {
sb.append("fun!")
assert(sb.toString === "ScalaTest is fun!")
}
}
In this example, the instance variable sb is a var, so it can
be reinitialized between tests. The runTest method, which is invoked
by execute for each test method to run, is overriden here such that
sb is first initialized. Then super.runTest is invoked, which
causes the test method to be run. Lastly, the fixture is “cleaned up” by clearing
the buffer.
Properties
In some cases you may need to pass information from a suite to its nested suites.
For example, perhaps a main suite needs to open a database connection that is then
used by all of its nested suites. You can accomplish this in ScalaTest by using
properties, which are passed to execute as a Map[String, Any].
This trait's execute method calls two other methods, both of which you
can override:
runNestedSuites - responsible for running this Suite's nested SuitesrunTests - responsible for running this Suite's tests
To pass custom properties to nested Suites, simply override runNestedSuites.
Here's an example:
import org.scalatest._
import java.io.FileWriter
class NestedSuite extends Suite {
override def execute(testName: Option[String], reporter: Reporter, stopper: Stopper,
includes: Set[String], excludes: Set[String], properties: Map[String, Any], distributor: Option[Distributor]) {
val w = properties("fixture.FileWriter").asInstanceOf[FileWriter]
w.write("hi there\n")
}
}
class MainSuite extends SuperSuite(new NestedSuite :: Nil) {
override def runNestedSuites(reporter: Reporter, stopper: Stopper, includes: Set[String],
excludes: Set[String], properties: Map[String, Any], distributor: Option[Distributor]) {
val w = new FileWriter("fixture.txt")
try {
val myProps = properties + ("fixture.FileWriter" -> w)
super.runNestedSuites(reporter, stopper, includes, excludes, myProps, distributor)
}
finally {
w.close()
}
}
}
In this example, MainSuite's runNestedSuites method opens a file for writing, then passes
the FileWriter to its NestedSuite via the properties Map. The NestedSuite
grabs the FileWriter from the properties Map and writes a friendly message to the file.
Suite set up and clean up
The previous example gives a hint at how you would accomplish the kind of intialization and cleanup in ScalaTest that
you would do with @BeforeClass and @AfterClass annotations in JUnit 4. If you want to
do something before and/or after all tests in a Suite, you
override runTests. Inside runTests, you first do what you need to do before all tests, then
call super.runTests, then do what you need to after all tests. For example, if you must open a file
before the tests are run, and close it after all the tests have completed, you could override the method like this:
import org.scalatest._
import java.io.FileReader
class MySuite extends Suite {
var reader: FileReader = _
protected override def runTests(testName: Option[String], reporter: Reporter, stopper: Stopper,
includes: Set[String], excludes: Set[String], properties: Map[String, Any]) {
reader = new FileReader("filename.txt")
try {
super.runTests(testName, reporter, stopper, includes, excludes, properties)
}
finally {
reader.close()
}
}
}
If you want to do something before and after both the tests and the nested Suites,
then override execute itself.
Test groups
A Suite's tests may be classified into named groups. When executing
a Suite, groups of tests can optionally be included and/or excluded. In this
trait's implementation, groups are indicated by annotations attached to the test method. To
create a group, simply define a new Java annotation. (Currently, for annotations to be
visible in Scala programs via Java reflection, the annotations themselves must be written in Java.) For example,
to create a group named SlowAsMolasses, to use to mark slow tests, you would
write in Java:
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface SlowAsMolasses {}
Given this new annotation, you could place methods into the SlowAsMolasses group
like this:
@SlowAsMolasses def testSleeping() = sleep(1000000)
The primary execute method takes two Set[String]s called includes and
excludes. If includes is empty, all tests will be executed
except those those belonging to groups listed in the
excludes Set. If includes is non-empty, only tests
belonging to groups mentioned in includes, and not mentioned in excludes,
will be executed.
Ignored tests
Another common use case is that tests must be “temporarily” disabled, with the
good intention of resurrecting the test at a later time. ScalaTest provides an Ignore
annotation for this purpose. You use it like this:
import org.scalatest.Suite
import org.scalatest.Ignore
class MySuite extends Suite {
def testAddition() {
val sum = 1 + 1
assert(sum === 2)
assert(sum + 2 === 4)
}
@Ignore
def testSubtraction() {
val diff = 4 - 1
assert(diff === 3)
assert(diff - 2 === 1)
}
}
If you run this version of MySuite with:
scala> (new MySuite).execute()
It will run only testAddition and report that testSubtraction was ignored.
Ignore is implemented as a group. The execute method that takes no parameters
adds org.scalatest.Ignore to the excludes Set it passes to
the primary execute method, as does Runner. The only difference between
org.scalatest.Ignore and the groups you may define and exclude is that ScalaTest reports
ignored tests to the Reporter. The reason ScalaTest reports ignored tests is as a feeble
attempt to encourage ignored tests to be eventually fixed and added back into the active suite of tests.
Reporters
One of the parameters to the primary execute method is a Reporter, which
will collect and report information about the running suite of tests.
Information about suites and tests that were run, whether tests succeeded or failed,
and tests that were ignored will be passed to the Reporter as the suite runs.
Most often the reporting done by default by Suite's methods will be sufficient, but
occasionally you may wish to provide custom information to the Reporter from a test method.
For this purpose, you can optionally include a Reporter parameter in a test method, and then
pass the extra information to the Reporter's infoProvided method.
Here's an example:
import org.scalatest._
class MySuite extends Suite {
def testAddition(reporter: Reporter) {
assert(1 + 1 === 2)
val report =
new Report("MySuite.testAddition(Reporter)", "Addition seems to work.")
reporter.infoProvided(report)
}
}
If you run this Suite from the interpreter, you will see the following message
included in the printed report:
Info Provided: MySuite.testAddition: Addition seems to work.
Executing suites concurrently
The primary execute method takes as its last parameter an optional Distributor. If
a Distributor is passed in, this trait's implementation of execute puts its nested
Suites into the distributor rather than executing them directly. The caller of execute
is responsible for ensuring that some entity executes the Suites placed into the
distributor. The -c command line parameter to Runner, for example, will cause
Suites put into the Distributor to be executed concurrently via a pool of threads.
Extensibility
Trait Suite provides default implementations of its methods that should
be sufficient for most applications, but many methods can be overridden when desired. Here's
a summary of the methods that are intended to be overridden, and why you might want to do so:
execute - override this method to define custom ways to executes suites of
tests. A common use case is to set up a fixture before running a suite of tests, and if needed, clean it up afterwords.runTest - override this method to define custom ways to execute a single named test. A common
use case is to set up a fixture before running each test in a suite, and if needed, clean it up afterwords. testNames - override this method to specify the Suite's test names in a custom way, such
as in a different order.groups - override this method to specify the Suite's test groups in a custom way.nestedSuites - override this method to specify the Suite's nested Suites in a custom way.suiteName - override this method to specify the Suite's name in a custom way.expectedTestCount - override this method to count this Suite's expected tests in a custom way.
For example, this trait's implementation of testNames performs reflection to discover methods starting with test,
and places these in a Set whose iterator returns the names in alphabetical order. If you wish to run tests in a different
order in a particular Suite, perhaps because a test named testAlpha can only succeed after a test named
testBeta has run, you can override testNames so that it returns a Set whose iterator returns
testBeta before testAlpha. (This trait's implementation of execute will invoke tests
in the order they come out of the testNames Set iterator.)
Alternatively, you may not like starting your test methods with test, and prefer using @Test annotations in
the style of Java's JUnit 4 or TestNG. If so, you can override testNames to discover tests using either of these two APIs
@Test annotations, or one of your own invention.
Moreover, test in ScalaTest does not necessarily mean test method. A test can be anything that can be given a name,
that starts and either succeeds or fails, and can be ignored. In a Scala test framework called Rehersal, for example, tests are represented
as function values. This
approach might look foreign to JUnit users, but may feel more natural to programmers with a functional programming background. If you
prefer this approach, you can override testNames, runTest, and execute such that you can
define tests as function values.
You can also model JUnit, JUnit 4, or TestNG tests as suites of tests, thereby incorporating existing Java tests into a ScalaTest suite.
If this turns out to be a common use case, we may later add wrapper suites to the API that will make this easy. The point here is that
no matter what legacy tests you may have, it is likely you can create our use an existing Suite subclass that allows you to model those tests
as ScalaTest suites and tests, to incorporate them into a ScalaTest suite. You can then write new tests in Scala and continue supporting
older tests in Java.
| Method Summary | |
def
|
assert
(o : scala.Option[java.lang.String], message : Any) : Unit
Assert that an
Option[String] is None.
If the condition is None, this method returns normally.
Else, it throws AssertionError with the String
value of the Some, as well as the
String obtained by invoking toString on the
specified message,
included in the AssertionError's detail message. |
def
|
assert
(condition : Boolean) : Unit
Assert that a boolean condition is true.
If the condition is
true, this method returns normally.
Else, it throws AssertionError. |
def
|
assert
(o : scala.Option[java.lang.String]) : Unit
Assert that an
Option[String] is None.
If the condition is None, this method returns normally.
Else, it throws AssertionError with the String
value of the Some included in the AssertionError's
detail message. |
def
|
assert
(condition : Boolean, message : Any) : Unit
Assert that a boolean condition, described in
String
message, is true.
If the condition is true, this method returns normally.
Else, it throws AssertionError with the
String obtained by invoking toString on the
specified message as the exception's detail message. |
implicit def
|
convertToEqualizer
(left : Any) : Equalizer
Implicit conversion from
Any to Equalizer, used to enable
assertions with === comparisons. For more information
on this mechanism, see the documentation for Equalizer. |
def
|
execute
(testName : scala.Option[java.lang.String], reporter : Reporter, stopper : Stopper, includes : scala.collection.immutable.Set[java.lang.String], excludes : scala.collection.immutable.Set[java.lang.String], properties : scala.collection.immutable.Map[java.lang.String, Any], distributor : scala.Option[Distributor]) : Unit
Execute this
Suite. |
final def
|
execute
: Unit
Executes this
Suite, printing results to the standard output. This method
implementation calls on this Suite the execute method that takes
seven parameters, passing in:
|
final def
|
execute
(testName : java.lang.String) : Unit
Executes the test specified
testName in this Suite, printing results to the standard output. This method
implementation calls on this Suite the execute method that takes
seven parameters, passing in:
|
def
|
expect
(expected : Any)(f : => Any) : Unit
Expect that the value passed as
expected equals the value resulting from the passed function f.
The expect method invokes the passed function. If the function results in a value that equals expected
(as determined by ==), expect returns
normally. Else, if the function results in a value that is not equal to expected, expect throws an
AssertionError whose detail message includes the expected and actual values.
If the function, completes abruptly an exception, the expect method will complete abruptly with that same exception. |
def
|
expect
(expected : Any, message : Any)(f : => Any) : Unit
Expect that the value passed as
expected equals the value resulting from the passed function f.
The expect method invokes the passed function. If the function results in a value that equals expected
(as determined by ==), expect returns
normally. Else, if the function results in a value that is not equal to expected, expect throws an
AssertionError whose detail message includes the expected and actual values, as well as the String
obtained by invoking toString on the passed message.
If the function, completes abruptly an exception, the expect method will complete abruptly with that same exception. |
def
|
expectedTestCount
(includes : scala.collection.immutable.Set[java.lang.String], excludes : scala.collection.immutable.Set[java.lang.String]) : Int
The total number of tests that are expected to run when this
Suite's execute method is invoked.
This trait's implementation of this method returns the sum of:
|
def
|
fail
: Nothing
Throws
AssertionError to indicate a test failed. |
def
|
fail
(cause : java.lang.Throwable) : Nothing
Throws
AssertionError, with the passed
Throwable cause, to indicate a test failed.
The getMessage method of the thrown AssertionError
will return cause.toString(). |
def
|
fail
(message : java.lang.String, cause : java.lang.Throwable) : Nothing
Throws
AssertionError, with the passed
String message as the exception's detail
message and Throwable cause, to indicate a test failed. |
def
|
fail
(message : java.lang.String) : Nothing
Throws
AssertionError, with the passed
String message as the exception's detail
message, to indicate a test failed. |
def
|
groups
: scala.collection.immutable.Map[java.lang.String, scala.collection.immutable.Set[java.lang.String]]
A
Map whose keys are String group names to which tests in this Suite belong, and values
the Set of test names that belong to each group. If this Suite contains no groups, this method returns an empty Map. |
def
|
intercept
(clazz : java.lang.Class[AnyRef])(f : => Unit) : java.lang.Throwable
Intercept and return an instance of the passed exception class (or an instance of a subclass of the
passed class), which is expected to be thrown by the passed function value. This method invokes the passed
function. If it throws an exception that's an instance of the passed class or one of its
subclasses, this method returns that exception. Else, whether the passed function returns normally
or completes abruptly with a different exception, this method throws
AssertionError. |
def
|
intercept
(clazz : java.lang.Class[AnyRef], message : Any)(f : => Unit) : java.lang.Throwable
Intercept and return an instance of the passed exception class (or an instance of a subclass of the
passed class), which is expected to be thrown by the passed function value. This method invokes the passed
function. If it throws an exception that's an instance of the passed class or one of its
subclasses, this method returns that exception. Else, whether the passed function returns normally
or completes abruptly with a different exception, this method throws
AssertionError
whose detail message includes the String obtained by invoking toString on the passed message. |
def
|
nestedSuites
: scala.List[Suite]
A
List of this Suite object's nested Suites. If this Suite contains no nested Suites,
this method returns an empty List. This trait's implementation of this method returns an empty List. |
protected def
|
runNestedSuites (reporter : Reporter, stopper : Stopper, includes : scala.collection.immutable.Set[java.lang.String], excludes : scala.collection.immutable.Set[java.lang.String], properties : scala.collection.immutable.Map[java.lang.String, Any], distributor : scala.Option[Distributor]) : Unit |
protected def
|
runTest
(testName : java.lang.String, reporter : Reporter, stopper : Stopper, properties : scala.collection.immutable.Map[java.lang.String, Any]) : Unit
Run a test. This trait's implementation uses Java reflection to invoke on this object the test method identified by the passed
testName. |
protected def
|
runTests (testName : scala.Option[java.lang.String], reporter : Reporter, stopper : Stopper, includes : scala.collection.immutable.Set[java.lang.String], excludes : scala.collection.immutable.Set[java.lang.String], properties : scala.collection.immutable.Map[java.lang.String, Any]) : Unit |
def
|
suiteName
: java.lang.String
A user-friendly suite name for this
Suite. This trait's
implementation of this method returns the simple name of this object's class. This
trait's implementation of runNestedSuites calls this method to obtain a
name for Reports to pass to the suiteStarting, suiteCompleted,
and suiteAborted methods of the Reporter. |
def
|
testNames
: scala.collection.immutable.Set[java.lang.String]
An immutable
Set of test names. If this Suite contains no tests, this method returns an empty Set. |
| Methods inherited from AnyRef | |
| getClass, hashCode, equals, clone, toString, notify, notifyAll, wait, wait, wait, finalize, ==, !=, eq, ne, synchronized |
| Methods inherited from Any | |
| ==, !=, isInstanceOf, asInstanceOf |
| Class Summary | |
class
|
Equalizer
(left : Any) extends AnyRef
Class used via an implicit conversion to enable any two objects to be compared with
=== in assertions in tests. For example:
assert(a === b) |
| Method Details |
def
nestedSuites : scala.List[Suite]
List of this Suite object's nested Suites. If this Suite contains no nested Suites,
this method returns an empty List. This trait's implementation of this method returns an empty List.final
def
execute : Unit
Suite, printing results to the standard output. This method
implementation calls on this Suite the execute method that takes
seven parameters, passing in:
testName - Nonereporter - a reporter that prints to the standard outputstopper - a Stopper whose stopRequested method always returns falseincludes - an empty Set[String]excludes - an Set[String] that contains only one element, "org.scalatest.Ignore"properties - an empty Map[String, Any]distributor - None
This method serves as a convenient way to execute a Suite, especially from within the Scala interpreter.
final
def
execute(testName : java.lang.String) : Unit
testName in this Suite, printing results to the standard output. This method
implementation calls on this Suite the execute method that takes
seven parameters, passing in:
testName - Some(testName)reporter - a reporter that prints to the standard outputstopper - a Stopper whose stopRequested method always returns falseincludes - an empty Set[String]excludes - an empty Set[String]properties - an empty Map[String, Any]distributor - NoneThis method serves as a convenient way to execute a single test, especially from within the Scala interpreter.
def
groups : scala.collection.immutable.Map[java.lang.String, scala.collection.immutable.Set[java.lang.String]]
Map whose keys are String group names to which tests in this Suite belong, and values
the Set of test names that belong to each group. If this Suite contains no groups, this method returns an empty Map.
This trait's implementation uses Java reflection to discover any Java annotations attached to its test methods. Each unique
annotation name is considered a group. This trait's implementation, therefore, places one key/value pair into to the
Map for each unique annotation name discovered through reflection. The value for each group name key will contain
the test method name, as provided via the testNames method.
Subclasses may override this method to define and/or discover groups in a custom manner, but overriding method implementations
should never return an empty Set as a value. If a group has no tests, its name should not appear as a key in the
returned Map.
def
testNames : scala.collection.immutable.Set[java.lang.String]
Set of test names. If this Suite contains no tests, this method returns an empty Set.
This trait's implementation of this method uses Java reflection to discover all public methods whose name starts with "test",
which take either nothing or a single Reporter as parameters. For each discovered test method, it assigns a test name
comprised of just the method name if the method takes no parameters, or the method name plus (Reporter) if the
method takes a Reporter. Here are a few method signatures and the names that this trait's implementation assigns them:
def testCat() {} // test name: "testCat"
def testCat(Reporter) {} // test name: "testCat(Reporter)"
def testDog() {} // test name: "testDog"
def testDog(Reporter) {} // test name: "testDog(Reporter)"
def test() {} // test name: "test"
def test(Reporter) {} // test name: "test(Reporter)"
This trait's implementation of this method returns an immutable Set of all such names, excluding the name
testName. The iterator obtained by invoking elements on this
returned Set will produce the test names in their natural order, as determined by String's
compareTo method.
This trait's implementation of runTests invokes this method
and calls runTest for each test name in the order they appear in the returned Set's iterator.
Although this trait's implementation of this method returns a Set whose iterator produces String
test names in a well-defined order, the contract of this method does not required a defined order. Subclasses are free to
override this method and return test names in an undefined order, or in a defined order that's different from String's
natural order.
Subclasses may override this method to produce test names in a custom manner. One potential reason to override testNames is
to execute tests in a different order, for example, to ensure that tests that depend on other tests are run after those other tests.
Another potential reason to override is to discover test methods annotated with JUnit 4 or TestNG @Test annotations. Or
a subclass could override this method and return a static, hard-coded Set of tests, etc.
protected
def
runTest(testName : java.lang.String, reporter : Reporter, stopper : Stopper, properties : scala.collection.immutable.Map[java.lang.String, Any]) : Unit
testName.testName - the name of one test to execute.reporter - the Reporter to which results will be reportedstopper - the Stopper that will be consulted to determine whether to stop execution early.properties - a Map of properties that can be used by the executing Suite of tests.NullPointerException - if any of testName, reporter, stopper, or properties is null.protected
def
runTests(testName : scala.Option[java.lang.String], reporter : Reporter, stopper : Stopper, includes : scala.collection.immutable.Set[java.lang.String], excludes : scala.collection.immutable.Set[java.lang.String], properties : scala.collection.immutable.Map[java.lang.String, Any]) : Unit
Run zero to many of this Suite's tests.
This method takes a testName parameter that optionally specifies a test to invoke.
If testName is Some, this trait's implementation of this method
invokes runTest on this object, passing in:
testName - the String value of the testName Option passed
to this methodreporter - the Reporter passed to this method, or one that wraps and delegates to itstopper - the Stopper passed to this method, or one that wraps and delegates to itproperties - the properties Map passed to this method, or one that wraps and delegates to it
This method takes a Set of group names that should be included (includes), and a Set
that should be excluded (excludes), when deciding which of this Suite's tests to execute.
If includes is empty, all tests will be executed
except those those belonging to groups listed in the excludes Set. If includes is non-empty, only tests
belonging to groups mentioned in includes, and not mentioned in excludes
will be executed. However, if testName is Some, includes and excludes are essentially ignored.
Only if testName is None will includes and excludes be consulted to
determine which of the tests named in the testNames Set should be run. This trait's implementation
behaves this way, and it is part of the general contract of this method, so all overridden forms of this method should behave
this way as well. For more information on trait groups, see the main documentation for this trait.
If testName is None, this trait's implementation of this method
invokes testNames on this Suite to get a Set of names of tests to potentially execute.
(A testNames value of None essentially acts as a wildcard that means all tests in
this Suite that are selected by includes and excludes should be executed.)
For each test in the testName Set, in the order
they appear in the iterator obtained by invoking the elements method on the Set, this trait's implementation
of this method checks whether the test should be run based on the includes and excludes Sets.
If so, this implementation invokes runTest, passing in:
testName - the String name of the test to run (which will be one of the names in the testNames Set)reporter - the Reporter passed to this method, or one that wraps and delegates to itstopper - the Stopper passed to this method, or one that wraps and delegates to itproperties - the properties Map passed to this method, or one that wraps and delegates to ittestName - an optional name of one test to execute. If None, all relevant tests should be executed. I.e., None acts like a wildcard that means execute all relevant tests in this Suite.reporter - the Reporter to which results will be reportedstopper - the Stopper that will be consulted to determine whether to stop execution early.includes - a Set of String test names to include in the execution of this Suiteexcludes - a Set of String test names to exclude in the execution of this Suiteproperties - a Map of properties that can be used by the executing Suite of tests.NullPointerException - if any of testName, reporter, stopper, includes, excludes, or properties is null.
This trait's implementation of this method executes tests
in the manner described in detail in the following paragraphs, but subclasses may override the method to provide different
behavior. The most common reason to override this method is to set up and, if also necessary, to clean up a test fixture
used by all the methods of this Suite.
def
execute(testName : scala.Option[java.lang.String], reporter : Reporter, stopper : Stopper, includes : scala.collection.immutable.Set[java.lang.String], excludes : scala.collection.immutable.Set[java.lang.String], properties : scala.collection.immutable.Map[java.lang.String, Any], distributor : scala.Option[Distributor]) : Unit
Suite.
If testName is None, this trait's implementation of this method
calls these two methods on this object in this order:
runNestedSuites(wrappedReporter, stopper, includes, excludes, properties, distributor)runTests(testName, wrappedReporter, stopper, includes, excludes, properties)
If testName is Some, then this trait's implementation of this method
calls runTests, but does not call runNestedSuites.
testName - an optional name of one test to execute. If None, all relevant tests should be executed. I.e., None acts like a wildcard that means execute all relevant tests in this Suite.reporter - the Reporter to which results will be reportedstopper - the Stopper that will be consulted to determine whether to stop execution early.includes - a Set of String test names to include in the execution of this Suiteexcludes - a Set of String test names to exclude in the execution of this Suiteproperties - a Map of properties that can be used by the executing Suite of tests.distributor - an optional Distributor, into which to put nested Suites to be executed by another entity, such as concurrently by a pool of threads. If None, nested Suites will be executed sequentially.NullPointerException - if any passed parameter is null.protected
def
runNestedSuites(reporter : Reporter, stopper : Stopper, includes : scala.collection.immutable.Set[java.lang.String], excludes : scala.collection.immutable.Set[java.lang.String], properties : scala.collection.immutable.Map[java.lang.String, Any], distributor : scala.Option[Distributor]) : Unit
Execute zero to many of this Suite's nested Suites.
If the passed distributor is None, this trait's
implementation of this method invokes execute on each
nested Suite in the List obtained by invoking nestedSuites.
If a nested Suite's execute
method completes abruptly with an exception, this trait's implementation of this
method reports that the Suite aborted and attempts to execute the
next nested Suite.
If the passed distributor is Some, this trait's implementation
puts each nested Suite
into the Distributor contained in the Some, in the order in which the
Suites appear in the List returned by nestedSuites.
reporter - the Reporter to which results will be reportedNullPointerException - if reporter is null.
def
suiteName : java.lang.String
Suite. This trait's
implementation of this method returns the simple name of this object's class. This
trait's implementation of runNestedSuites calls this method to obtain a
name for Reports to pass to the suiteStarting, suiteCompleted,
and suiteAborted methods of the Reporter.Suite object's suite name.
def
expectedTestCount(includes : scala.collection.immutable.Set[java.lang.String], excludes : scala.collection.immutable.Set[java.lang.String]) : Int
Suite's execute method is invoked.
This trait's implementation of this method returns the sum of:
testNames List
expecteTestCount on every nested Suite contained in
nestedSuites
def
fail : Nothing
AssertionError to indicate a test failed.
def
fail(message : java.lang.String) : Nothing
AssertionError, with the passed
String message as the exception's detail
message, to indicate a test failed.message - A message describing the failure.NullPointerException - if message is null
def
fail(message : java.lang.String, cause : java.lang.Throwable) : Nothing
AssertionError, with the passed
String message as the exception's detail
message and Throwable cause, to indicate a test failed.message - A message describing the failure.cause - A Throwable that indicates the cause of the failure.NullPointerException - if message or cause is null
def
fail(cause : java.lang.Throwable) : Nothing
AssertionError, with the passed
Throwable cause, to indicate a test failed.
The getMessage method of the thrown AssertionError
will return cause.toString().cause - a Throwable that indicates the cause of the failure.NullPointerException - if cause is nulltrue, this method returns normally.
Else, it throws AssertionError.condition - the boolean condition to assertAssertionError - if the condition is false.String
message, is true.
If the condition is true, this method returns normally.
Else, it throws AssertionError with the
String obtained by invoking toString on the
specified message as the exception's detail message.condition - the boolean condition to assertmessage - An objects whose toString method returns a message to include in a failure report.AssertionError - if the condition is false.NullPointerException - if message is null.
def
assert(o : scala.Option[java.lang.String], message : Any) : Unit
Option[String] is None.
If the condition is None, this method returns normally.
Else, it throws AssertionError with the String
value of the Some, as well as the
String obtained by invoking toString on the
specified message,
included in the AssertionError's detail message.
This form of assert is usually called in conjunction with an
implicit conversion to Equalizer, using a === comparison, as in:
assert(a === b, "extra info reported if assertion fails")
For more information on how this mechanism works, see the documentation for
Equalizer.
o - the Option[String] to assertmessage - An objects whose toString method returns a message to include in a failure report.AssertionError - if the Option[String] is Some.NullPointerException - if message is null.
def
assert(o : scala.Option[java.lang.String]) : Unit
Option[String] is None.
If the condition is None, this method returns normally.
Else, it throws AssertionError with the String
value of the Some included in the AssertionError's
detail message.
This form of assert is usually called in conjunction with an
implicit conversion to Equalizer, using a === comparison, as in:
assert(a === b)
For more information on how this mechanism works, see the documentation for
Equalizer.
o - the Option[String] to assertAssertionError - if the Option[String] is Some.Any to Equalizer, used to enable
assertions with === comparisons. For more information
on this mechanism, see the documentation for Equalizer.left - the object whose type to convert to Equalizer.NullPointerException - if left is null.
def
intercept(clazz : java.lang.Class[AnyRef], message : Any)(f : => Unit) : java.lang.Throwable
AssertionError
whose detail message includes the String obtained by invoking toString on the passed message.
Note that the passed Class may represent any type, not just Throwable or one of its subclasses. In
Scala, exceptions can be caught based on traits they implement, so it may at times make sense to pass in a class instance for
a trait. If a class instance is passed for a type that could not possibly be used to catch an exception (such as String,
for example), this method will complete abruptly with an AssertionError.
clazz - a type to which the expected exception class is assignable, i.e., the exception should be an instance of the type represented by clazz.message - An objects whose toString method returns a message to include in a failure report.f - the function value that should throw the expected exceptionAssertionError - if the passed function does not result in a value equal to the passed expected value.
def
intercept(clazz : java.lang.Class[AnyRef])(f : => Unit) : java.lang.Throwable
AssertionError.
Note that the passed Class may represent any type, not just Throwable or one of its subclasses. In
Scala, exceptions can be caught based on traits they implement, so it may at times make sense to pass in a class instance for
a trait. If a class instance is passed for a type that could not possibly be used to catch an exception (such as String,
for example), this method will complete abruptly with an AssertionError.
clazz - a type to which the expected exception class is assignable, i.e., the exception should be an instance of the type represented by clazz.f - the function value that should throw the expected exceptionAssertionError - if the passed function does not complete abruptly with an exception that is assignable to the passed Class.IllegalArgumentException - if the passed clazz is not Throwable or one of its subclasses.expected equals the value resulting from the passed function f.
The expect method invokes the passed function. If the function results in a value that equals expected
(as determined by ==), expect returns
normally. Else, if the function results in a value that is not equal to expected, expect throws an
AssertionError whose detail message includes the expected and actual values, as well as the String
obtained by invoking toString on the passed message.
If the function, completes abruptly an exception, the expect method will complete abruptly with that same exception.expected - the expected result of the passed functionmessage - An objects whose toString method returns a message to include in a failure report.f - the function value whose result when invoked should equal the passed expected valueAssertionError - if the passed function does not complete abruptly with an exception that is assignable to the passed Class.expected equals the value resulting from the passed function f.
The expect method invokes the passed function. If the function results in a value that equals expected
(as determined by ==), expect returns
normally. Else, if the function results in a value that is not equal to expected, expect throws an
AssertionError whose detail message includes the expected and actual values.
If the function, completes abruptly an exception, the expect method will complete abruptly with that same exception.expected - the expected result of the passed functionf - the function value whose result when invoked should equal the passed expected valueAssertionError - if the passed function does not complete abruptly with an exception that is assignable to the passed Class.|
ScalaTest 0.9.2
|
|