trait Assertions extends TripleEquals
Trait that contains ScalaTest's basic assertion methods.
You can use the assertions provided by this trait in any ScalaTest Suite,
because Suite
mixes in this trait. This trait is designed to be used independently of anything else in ScalaTest, though, so you
can mix it into anything. (You can alternatively import the methods defined in this trait. For details, see the documentation
for the Assertions companion object.
In any Scala program, 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,
Scala's assert will complete abruptly with an AssertionError. This behavior is provided by
the assert method defined in object Predef, whose members are implicitly imported into every
Scala source file. This Assertions trait defines another assert method that hides the
one in Predef. It behaves the same, except that if false is passed it throws
TestFailedException instead of AssertionError.
Why? Because unlike AssertionError, TestFailedException carries information about exactly
which item in the stack trace represents
the line of test code that failed, which can help users more quickly find an offending line of code in a failing test.
In addition, ScalaTest's assert provides better error messages than Scala's assert.
If you pass the previous Boolean expression, left == right to assert in a ScalaTest test,
a failure will be reported that, because assert is implemented as a macro,
includes reporting the left and right values.
For example, given the same code as above but using ScalaTest assertions:
import org.scalatest.Assertions._ val left = 2 val right = 1 assert(left == right)
The detail message in the thrown TestFailedException from this assert
will be: "2 did not equal 1".
ScalaTest's assert macro works by recognizing patterns in the AST of the expression passed to assert and,
for a finite set of common expressions, giving an error message that an equivalent ScalaTest matcher
expression would give. Here are some examples, where a is 1, b is 2, c is 3, d
is 4, xs is List(a, b, c), and num is 1.0:
assert(a == b || c >= d) // Error message: 1 did not equal 2, and 3 was not greater than or equal to 4
assert(xs.exists(_ == 4)) // Error message: List(1, 2, 3) did not contain 4
assert("hello".startsWith("h") && "goodbye".endsWith("y")) // Error message: "hello" started with "h", but "goodbye" did not end with "y"
assert(num.isInstanceOf[Int]) // Error message: 1.0 was not instance of scala.Int
assert(Some(2).isEmpty) // Error message: Some(2) was not empty
For expressions that are not recognized, the macro currently prints out a string
representation of the (desugared) AST and adds "was false". Here are some examples of
error messages for unrecognized expressions:
assert(None.isDefined) // Error message: scala.None.isDefined was false
assert(xs.exists(i => i > 10)) // Error message: xs.exists(((i: Int) => i.>(10))) was false
You can augment the standard error message by providing a String as a second argument
to assert, like this:
val attempted = 2 assert(attempted == 1, "Execution was attempted " + attempted + " times instead of 1 time")
Using this form of assert, the failure report will be more specific to your problem domain, thereby
helping you debug the problem. This Assertions trait also mixes in the
TripleEquals, which gives you a === operator
that allows you to customize Equality, perform equality checks with numeric
Tolerance, and enforce type constraints at compile time with
sibling traits TypeCheckedTripleEquals and
ConversionCheckedTripleEquals.
Expected results
Although the assert macro provides a natural, readable extension to Scala's assert mechanism that
provides good error messages, as the operands become lengthy, the code becomes less readable. In addition, the error messages
generated for == and === comparisons
don'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 assertResult that
can be used as an alternative to assert. To use assertResult, you place
the expected value in parentheses after assertResult, followed by curly braces containing code
that should result in the expected value. For example:
val a = 5 val b = 2 assertResult(2) { a - b }
In this case, the expected value is 2, and the code being tested is a - b. This assertion will fail, and
the detail message in the TestFailedException will read, "Expected 2, but got 3."
Forcing failures
If you just need the test to fail, you can write:
fail()
Or, if you want the test to fail with a message, write:
fail("I've got a bad feeling about this")
Achieving success
In async style tests, you must end your test body with either Future[Assertion] or
Assertion. ScalaTest's assertions (including matcher expressions) have result type
Assertion, so ending with an assertion will satisfy the compiler.
If a test body or function body passed to Future.map does
not end with type Assertion, however, you can fix the type error by placing
succeed at the end of the
test or function body:
succeed // Has type Assertion
Expected 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 3 style, like this:
val s = "hi" try { s.charAt(-1) fail() } catch { case _: IndexOutOfBoundsException => // Expected, so continue }
If charAt throws IndexOutOfBoundsException as expected, control will transfer
to the catch case, which does nothing. If, however, charAt fails to throw an exception,
the next statement, fail(), will be run. The fail method always completes abruptly with
a TestFailedException, thereby signaling a failed test.
To make this common use case easier to express and read, ScalaTest provides two methods:
assertThrows and intercept.
Here's how you use assertThrows:
val s = "hi" assertThrows[IndexOutOfBoundsException] { // Result type: Assertion s.charAt(-1) }
This code behaves much like the previous example. If charAt throws an instance of IndexOutOfBoundsException,
assertThrows will return Succeeded. But if charAt completes normally, or throws a different
exception, assertThrows will complete abruptly with a TestFailedException.
The intercept method behaves the same as assertThrows, except that instead of returning Succeeded,
intercept returns the caught exception so that you can inspect it further if you wish. For example, you may need
to ensure that data contained inside the exception have expected values. Here's an example:
val s = "hi" val caught = intercept[IndexOutOfBoundsException] { // Result type: IndexOutOfBoundsException s.charAt(-1) } assert(caught.getMessage.indexOf("-1") != -1)
Checking that a snippet of code does or does not compile
Often when creating libraries you may wish to ensure that certain arrangements of code that
represent potential “user errors” do not compile, so that your library is more error resistant.
ScalaTest's Assertions trait includes the following syntax for that purpose:
assertDoesNotCompile("val a: String = 1")
If you want to ensure that a snippet of code does not compile because of a type error (as opposed to a syntax error), use:
assertTypeError("val a: String = 1")
Note that the assertTypeError call will only succeed if the given snippet of code does not
compile because of a type error. A syntax error will still result on a thrown TestFailedException.
If you want to state that a snippet of code does compile, you can make that more obvious with:
assertCompiles("val a: Int = 1")
Although the previous three constructs are implemented with macros that determine at compile time whether the snippet of code represented by the string does or does not compile, errors are reported as test failures at runtime.
Assumptions
Trait Assertions also provides methods that allow you to cancel a test.
You would cancel a test if a resource required by the test was unavailable. For example, if a test
requires an external database to be online, and it isn't, the test could be canceled to indicate
it was unable to run because of the missing database. Such a test assumes a database is
available, and you can use the assume method to indicate this at the beginning of
the test, like this:
assume(database.isAvailable)
For each overloaded assert method, trait Assertions provides an
overloaded assume method with an identical signature and behavior, except the
assume methods throw TestCanceledException whereas the
assert methods throw TestFailedException. As with assert,
assume hides a Scala method in Predef that performs a similar
function, but throws AssertionError. And just as you can with assert,
you will get an error message extracted by a macro from the AST passed to assume, and can
optionally provide a clue string to augment this error message. Here are some examples:
assume(database.isAvailable, "The database was down again") assume(database.getAllUsers.count === 9)
Forcing cancelations
For each overloaded fail method, there's a corresponding cancel method
with an identical signature and behavior, except the cancel methods throw
TestCanceledException whereas the fail methods throw
TestFailedException. Thus if you just need to cancel a test, you can write:
cancel()
If you want to cancel the test with a message, just place the message in the parentheses:
cancel("Can't run the test because no internet connection was found")
Getting a clue
If you want more information that is provided by default by the methods if this trait,
you can supply a "clue" string in one of several ways.
The extra information (or "clues") you provide will
be included in the detail message of the thrown exception. Both
assert and assertResult provide a way for a clue to be
included directly, intercept does not.
Here's an example of clues provided directly in assert:
assert(1 + 1 === 3, "this is a clue")
and in assertResult:
assertResult(3, "this is a clue") { 1 + 1 }
The exceptions thrown by the previous two statements will include the clue
string, "this is a clue", in the exception's detail message.
To get the same clue in the detail message of an exception thrown
by a failed intercept call requires using withClue:
withClue("this is a clue") { intercept[IndexOutOfBoundsException] { "hi".charAt(-1) } }
The withClue method will only prepend the clue string to the detail
message of exception types that mix in the ModifiableMessage trait.
See the documentation for ModifiableMessage for more information.
If you wish to place a clue string after a block of code, see the documentation for
AppendedClues.
Note: ScalaTest's assertTypeError construct is in part inspired by the illTyped macro
of shapeless.
- Source
- Assertions.scala
- Alphabetic
- By Inheritance
- Assertions
- TripleEquals
- TripleEqualsSupport
- AnyRef
- Any
- Hide All
- Show All
- Public
- Protected
Type Members
Value Members
- final def !=(arg0: Any): Boolean
- Definition Classes
- AnyRef → Any
- def !==[T](right: Spread[T]): TripleEqualsInvocationOnSpread[T]
- Definition Classes
- TripleEqualsSupport
- def !==(right: Null): TripleEqualsInvocation[Null]
- Definition Classes
- TripleEqualsSupport
- def !==[T](right: T): TripleEqualsInvocation[T]
- Definition Classes
- TripleEqualsSupport
- final def ##(): Int
- Definition Classes
- AnyRef → Any
- final def ==(arg0: Any): Boolean
- Definition Classes
- AnyRef → Any
- def ===[T](right: Spread[T]): TripleEqualsInvocationOnSpread[T]
- Definition Classes
- TripleEqualsSupport
- def ===(right: Null): TripleEqualsInvocation[Null]
- Definition Classes
- TripleEqualsSupport
- def ===[T](right: T): TripleEqualsInvocation[T]
- Definition Classes
- TripleEqualsSupport
- final def asInstanceOf[T0]: T0
- Definition Classes
- Any
- macro def assert(condition: Boolean, clue: Any)(implicit prettifier: Prettifier, pos: Position): Assertion
Assert that a boolean condition, described in
Stringmessage, is true.Assert that a boolean condition, described in
Stringmessage, is true. If the condition istrue, this method returns normally. Else, it throwsTestFailedExceptionwith a helpful error message appended with theStringobtained by invokingtoStringon the specifiedclueas the exception's detail message.This method is implemented in terms of a Scala macro that will generate a more helpful error message for expressions of this form:
- assert(a == b, "a good clue")
- assert(a != b, "a good clue")
- assert(a === b, "a good clue")
- assert(a !== b, "a good clue")
- assert(a > b, "a good clue")
- assert(a >= b, "a good clue")
- assert(a < b, "a good clue")
- assert(a <= b, "a good clue")
- assert(a startsWith "prefix", "a good clue")
- assert(a endsWith "postfix", "a good clue")
- assert(a contains "something", "a good clue")
- assert(a eq b, "a good clue")
- assert(a ne b, "a good clue")
- assert(a > 0 && b > 5, "a good clue")
- assert(a > 0 || b > 5, "a good clue")
- assert(a.isEmpty, "a good clue")
- assert(!a.isEmpty, "a good clue")
- assert(a.isInstanceOf[String], "a good clue")
- assert(a.length == 8, "a good clue")
- assert(a.size == 8, "a good clue")
- assert(a.exists(_ == 8), "a good clue")
At this time, any other form of expression will just get a
TestFailedExceptionwith message saying the given expression was false. In the future, we will enhance this macro to give helpful error messages in more situations. In ScalaTest 2.0, however, this behavior was sufficient to allow the===that returnsBooleanto be the default in tests. This makes===consistent between tests and production code.- condition
the boolean condition to assert
- clue
An objects whose
toStringmethod returns a message to include in a failure report.
- Exceptions thrown
NullArgumentExceptionifmessageisnull.TestFailedExceptionif the condition isfalse.
- macro def assert(condition: Boolean)(implicit prettifier: Prettifier, pos: Position): Assertion
Assert that a boolean condition is true.
Assert that a boolean condition is true. If the condition is
true, this method returns normally. Else, it throwsTestFailedException.This method is implemented in terms of a Scala macro that will generate a more helpful error message for expressions of this form:
- assert(a == b)
- assert(a != b)
- assert(a === b)
- assert(a !== b)
- assert(a > b)
- assert(a >= b)
- assert(a < b)
- assert(a <= b)
- assert(a startsWith "prefix")
- assert(a endsWith "postfix")
- assert(a contains "something")
- assert(a eq b)
- assert(a ne b)
- assert(a > 0 && b > 5)
- assert(a > 0 || b > 5)
- assert(a.isEmpty)
- assert(!a.isEmpty)
- assert(a.isInstanceOf[String])
- assert(a.length == 8)
- assert(a.size == 8)
- assert(a.exists(_ == 8))
At this time, any other form of expression will get a
TestFailedExceptionwith message saying the given expression was false. In the future, we will enhance this macro to give helpful error messages in more situations. In ScalaTest 2.0, however, this behavior was sufficient to allow the===that returnsBooleanto be the default in tests. This makes===consistent between tests and production code.- condition
the boolean condition to assert
- Exceptions thrown
TestFailedExceptionif the condition isfalse.
- macro def assertCompiles(code: String)(implicit pos: Position): Assertion
Asserts that a given string snippet of code passes both the Scala parser and type checker.
Asserts that a given string snippet of code passes both the Scala parser and type checker.
You can use this to make sure a snippet of code compiles:
assertCompiles("val a: Int = 1")Although
assertCompilesis implemented with a macro that determines at compile time whether the snippet of code represented by the passed string compiles, errors (i.e., snippets of code that do not compile) are reported as test failures at runtime.- code
the snippet of code that should compile
- macro def assertDoesNotCompile(code: String)(implicit pos: Position): Assertion
Asserts that a given string snippet of code does not pass either the Scala parser or type checker.
Asserts that a given string snippet of code does not pass either the Scala parser or type checker.
Often when creating libraries you may wish to ensure that certain arrangements of code that represent potential “user errors” do not compile, so that your library is more error resistant. ScalaTest's
Assertionstrait includes the following syntax for that purpose:assertDoesNotCompile("val a: String = \"a string")Although
assertDoesNotCompileis implemented with a macro that determines at compile time whether the snippet of code represented by the passed string doesn't compile, errors (i.e., snippets of code that do compile) are reported as test failures at runtime.Note that the difference between
assertTypeErrorandassertDoesNotCompileis thatassertDoesNotCompilewill succeed if the given code does not compile for any reason, whereasassertTypeErrorwill only succeed if the given code does not compile because of a type error. If the given code does not compile because of a syntax error, for example,assertDoesNotCompilewill return normally butassertTypeErrorwill throw aTestFailedException.- code
the snippet of code that should not type check
- def assertResult(expected: Any)(actual: Any)(implicit prettifier: Prettifier, pos: Position): Assertion
Assert that the value passed as
expectedequals the value passed asactual.Assert that the value passed as
expectedequals the value passed asactual. If theactualvalue equals theexpectedvalue (as determined by==),assertResultreturns normally. Else,assertResultthrows aTestFailedExceptionwhose detail message includes the expected and actual values.- expected
the expected value
- actual
the actual value, which should equal the passed
expectedvalue
- Exceptions thrown
TestFailedExceptionif the passedactualvalue does not equal the passedexpectedvalue.
- def assertResult(expected: Any, clue: Any)(actual: Any)(implicit prettifier: Prettifier, pos: Position): Assertion
Assert that the value passed as
expectedequals the value passed asactual.Assert that the value passed as
expectedequals the value passed asactual. If theactualequals theexpected(as determined by==),assertResultreturns normally. Else, ifactualis not equal toexpected,assertResultthrows aTestFailedExceptionwhose detail message includes the expected and actual values, as well as theStringobtained by invokingtoStringon the passedclue.- expected
the expected value
- clue
An object whose
toStringmethod returns a message to include in a failure report.- actual
the actual value, which should equal the passed
expectedvalue
- Exceptions thrown
TestFailedExceptionif the passedactualvalue does not equal the passedexpectedvalue.
- def assertThrows[T <: AnyRef](f: => Any)(implicit classTag: ClassTag[T], pos: Position): Assertion
Ensure that an expected exception is thrown by the passed function value.
Ensure that an expected exception is thrown by the passed function value. The thrown exception must be an instance of the type specified by the type parameter of this method. This method invokes the passed function. If the function throws an exception that's an instance of the specified type, this method returns
Succeeded. Else, whether the passed function returns normally or completes abruptly with a different exception, this method throwsTestFailedException.Note that the type specified as this method's type parameter may represent any subtype of
AnyRef, not justThrowableor one of its subclasses. In Scala, exceptions can be caught based on traits they implement, so it may at times make sense to specify a trait that the intercepted exception's class must mix in. If a class instance is passed for a type that could not possibly be used to catch an exception (such asString, for example), this method will complete abruptly with aTestFailedException.Also note that the difference between this method and
interceptis that this method does not return the expected exception, so it does not let you perform further assertions on that exception. Instead, this method returnsSucceeded, which means it can serve as the last statement in an async- or safe-style suite. It also indicates to the reader of the code that nothing further is expected about the thrown exception other than its type. The recommended usage is to useassertThrowsby default,interceptonly when you need to inspect the caught exception further.- f
the function value that should throw the expected exception
- classTag
an implicit
ClassTagrepresenting the type of the specified type parameter.- returns
the
Succeededsingleton, if an exception of the expected type is thrown
- Exceptions thrown
TestFailedExceptionif the passed function does not complete abruptly with an exception that's an instance of the specified type.
- macro def assertTypeError(code: String)(implicit pos: Position): Assertion
Asserts that a given string snippet of code does not pass the Scala type checker, failing if the given snippet does not pass the Scala parser.
Asserts that a given string snippet of code does not pass the Scala type checker, failing if the given snippet does not pass the Scala parser.
Often when creating libraries you may wish to ensure that certain arrangements of code that represent potential “user errors” do not compile, so that your library is more error resistant. ScalaTest's
Assertionstrait includes the following syntax for that purpose:assertTypeError("val a: String = 1")Although
assertTypeErroris implemented with a macro that determines at compile time whether the snippet of code represented by the passed string type checks, errors (i.e., snippets of code that do type check) are reported as test failures at runtime.Note that the difference between
assertTypeErrorandassertDoesNotCompileis thatassertDoesNotCompilewill succeed if the given code does not compile for any reason, whereasassertTypeErrorwill only succeed if the given code does not compile because of a type error. If the given code does not compile because of a syntax error, for example,assertDoesNotCompilewill return normally butassertTypeErrorwill throw aTestFailedException.- code
the snippet of code that should not type check
- macro def assume(condition: Boolean, clue: Any)(implicit prettifier: Prettifier, pos: Position): Assertion
Assume that a boolean condition, described in
Stringmessage, is true.Assume that a boolean condition, described in
Stringmessage, is true. If the condition istrue, this method returns normally. Else, it throwsTestCanceledExceptionwith a helpful error message appended withStringobtained by invokingtoStringon the specifiedclueas the exception's detail message.This method is implemented in terms of a Scala macro that will generate a more helpful error message for expressions of this form:
- assume(a == b, "a good clue")
- assume(a != b, "a good clue")
- assume(a === b, "a good clue")
- assume(a !== b, "a good clue")
- assume(a > b, "a good clue")
- assume(a >= b, "a good clue")
- assume(a < b, "a good clue")
- assume(a <= b, "a good clue")
- assume(a startsWith "prefix", "a good clue")
- assume(a endsWith "postfix", "a good clue")
- assume(a contains "something", "a good clue")
- assume(a eq b, "a good clue")
- assume(a ne b, "a good clue")
- assume(a > 0 && b > 5, "a good clue")
- assume(a > 0 || b > 5, "a good clue")
- assume(a.isEmpty, "a good clue")
- assume(!a.isEmpty, "a good clue")
- assume(a.isInstanceOf[String], "a good clue")
- assume(a.length == 8, "a good clue")
- assume(a.size == 8, "a good clue")
- assume(a.exists(_ == 8), "a good clue")
At this time, any other form of expression will just get a
TestCanceledExceptionwith message saying the given expression was false. In the future, we will enhance this macro to give helpful error messages in more situations. In ScalaTest 2.0, however, this behavior was sufficient to allow the===that returnsBooleanto be the default in tests. This makes===consistent between tests and production code.- condition
the boolean condition to assume
- clue
An objects whose
toStringmethod returns a message to include in a failure report.
- Exceptions thrown
NullArgumentExceptionifmessageisnull.TestCanceledExceptionif the condition isfalse.
- macro def assume(condition: Boolean)(implicit prettifier: Prettifier, pos: Position): Assertion
Assume that a boolean condition is true.
Assume that a boolean condition is true. If the condition is
true, this method returns normally. Else, it throwsTestCanceledException.This method is implemented in terms of a Scala macro that will generate a more helpful error message for expressions of this form:
- assume(a == b)
- assume(a != b)
- assume(a === b)
- assume(a !== b)
- assume(a > b)
- assume(a >= b)
- assume(a < b)
- assume(a <= b)
- assume(a startsWith "prefix")
- assume(a endsWith "postfix")
- assume(a contains "something")
- assume(a eq b)
- assume(a ne b)
- assume(a > 0 && b > 5)
- assume(a > 0 || b > 5)
- assume(a.isEmpty)
- assume(!a.isEmpty)
- assume(a.isInstanceOf[String])
- assume(a.length == 8)
- assume(a.size == 8)
- assume(a.exists(_ == 8))
At this time, any other form of expression will just get a
TestCanceledExceptionwith message saying the given expression was false. In the future, we will enhance this macro to give helpful error messages in more situations. In ScalaTest 2.0, however, this behavior was sufficient to allow the===that returnsBooleanto be the default in tests. This makes===consistent between tests and production code.- condition
the boolean condition to assume
- Exceptions thrown
TestCanceledExceptionif the condition isfalse.
- def cancel(cause: Throwable)(implicit pos: Position): Nothing
Throws
TestCanceledException, with the passedThrowablecause, to indicate a test failed.Throws
TestCanceledException, with the passedThrowablecause, to indicate a test failed. ThegetMessagemethod of the thrownTestCanceledExceptionwill returncause.toString.- cause
a
Throwablethat indicates the cause of the cancellation.
- Exceptions thrown
NullArgumentExceptionifcauseisnull
- def cancel(message: String, cause: Throwable)(implicit pos: Position): Nothing
Throws
TestCanceledException, with the passedStringmessageas the exception's detail message andThrowablecause, to indicate a test failed.Throws
TestCanceledException, with the passedStringmessageas the exception's detail message andThrowablecause, to indicate a test failed.- message
A message describing the failure.
- cause
A
Throwablethat indicates the cause of the failure.
- Exceptions thrown
NullArgumentExceptionifmessageorcauseisnull
- def cancel(message: String)(implicit pos: Position): Nothing
Throws
TestCanceledException, with the passedStringmessageas the exception's detail message, to indicate a test was canceled.Throws
TestCanceledException, with the passedStringmessageas the exception's detail message, to indicate a test was canceled.- message
A message describing the cancellation.
- Exceptions thrown
NullArgumentExceptionifmessageisnull
- def cancel()(implicit pos: Position): Nothing
Throws
TestCanceledExceptionto indicate a test was canceled. - def clone(): AnyRef
- Attributes
- protected[lang]
- Definition Classes
- AnyRef
- Annotations
- @throws(classOf[java.lang.CloneNotSupportedException]) @native()
- def convertEquivalenceToAToBConstraint[A, B](equivalenceOfB: Equivalence[B])(implicit ev: <:<[A, B]): CanEqual[A, B]
- Definition Classes
- TripleEquals → TripleEqualsSupport
- def convertEquivalenceToBToAConstraint[A, B](equivalenceOfA: Equivalence[A])(implicit ev: <:<[B, A]): CanEqual[A, B]
- Definition Classes
- TripleEquals → TripleEqualsSupport
- def convertToCheckingEqualizer[T](left: T): CheckingEqualizer[T]
- Definition Classes
- TripleEquals → TripleEqualsSupport
- implicit def convertToEqualizer[T](left: T): Equalizer[T]
- Definition Classes
- TripleEquals → TripleEqualsSupport
- def defaultEquality[A]: Equality[A]
- Definition Classes
- TripleEqualsSupport
- final def eq(arg0: AnyRef): Boolean
- Definition Classes
- AnyRef
- def equals(arg0: AnyRef): Boolean
- Definition Classes
- AnyRef → Any
- def fail(cause: Throwable)(implicit pos: Position): Nothing
Throws
TestFailedException, with the passedThrowablecause, to indicate a test failed.Throws
TestFailedException, with the passedThrowablecause, to indicate a test failed. ThegetMessagemethod of the thrownTestFailedExceptionwill returncause.toString.- cause
a
Throwablethat indicates the cause of the failure.
- Exceptions thrown
NullArgumentExceptionifcauseisnull
- def fail(message: String, cause: Throwable)(implicit pos: Position): Nothing
Throws
TestFailedException, with the passedStringmessageas the exception's detail message andThrowablecause, to indicate a test failed.Throws
TestFailedException, with the passedStringmessageas the exception's detail message andThrowablecause, to indicate a test failed.- message
A message describing the failure.
- cause
A
Throwablethat indicates the cause of the failure.
- Exceptions thrown
NullArgumentExceptionifmessageorcauseisnull
- def fail(message: String)(implicit pos: Position): Nothing
Throws
TestFailedException, with the passedStringmessageas the exception's detail message, to indicate a test failed.Throws
TestFailedException, with the passedStringmessageas the exception's detail message, to indicate a test failed.- message
A message describing the failure.
- Exceptions thrown
NullArgumentExceptionifmessageisnull
- def fail()(implicit pos: Position): Nothing
Throws
TestFailedExceptionto indicate a test failed. - def finalize(): Unit
- Attributes
- protected[lang]
- Definition Classes
- AnyRef
- Annotations
- @throws(classOf[java.lang.Throwable])
- final def getClass(): Class[_ <: AnyRef]
- Definition Classes
- AnyRef → Any
- Annotations
- @native()
- def hashCode(): Int
- Definition Classes
- AnyRef → Any
- Annotations
- @native()
- def intercept[T <: AnyRef](f: => Any)(implicit classTag: ClassTag[T], pos: Position): T
Intercept and return an exception that's expected to be thrown by the passed function value.
Intercept and return an exception that's expected to be thrown by the passed function value. The thrown exception must be an instance of the type specified by the type parameter of this method. This method invokes the passed function. If the function throws an exception that's an instance of the specified type, this method returns that exception. Else, whether the passed function returns normally or completes abruptly with a different exception, this method throws
TestFailedException.Note that the type specified as this method's type parameter may represent any subtype of
AnyRef, not justThrowableor one of its subclasses. In Scala, exceptions can be caught based on traits they implement, so it may at times make sense to specify a trait that the intercepted exception's class must mix in. If a class instance is passed for a type that could not possibly be used to catch an exception (such asString, for example), this method will complete abruptly with aTestFailedException.Also note that the difference between this method and
assertThrowsis that this method returns the expected exception, so it lets you perform further assertions on that exception. By contrast, theassertThrowsmethod returnsSucceeded, which means it can serve as the last statement in an async- or safe-style suite.assertThrowsalso indicates to the reader of the code that nothing further is expected about the thrown exception other than its type. The recommended usage is to useassertThrowsby default,interceptonly when you need to inspect the caught exception further.- f
the function value that should throw the expected exception
- classTag
an implicit
ClassTagrepresenting the type of the specified type parameter.- returns
the intercepted exception, if it is of the expected type
- Exceptions thrown
TestFailedExceptionif the passed function does not complete abruptly with an exception that's an instance of the specified type.
- final def isInstanceOf[T0]: Boolean
- Definition Classes
- Any
- def lowPriorityTypeCheckedConstraint[A, B](implicit equivalenceOfB: Equivalence[B], ev: <:<[A, B]): CanEqual[A, B]
- Definition Classes
- TripleEquals → TripleEqualsSupport
- final def ne(arg0: AnyRef): Boolean
- Definition Classes
- AnyRef
- final def notify(): Unit
- Definition Classes
- AnyRef
- Annotations
- @native()
- final def notifyAll(): Unit
- Definition Classes
- AnyRef
- Annotations
- @native()
- def pending: Assertion with PendingStatement
Throws
TestPendingExceptionto indicate a test is pending.Throws
TestPendingExceptionto indicate a test is pending.A pending test is one that has been given a name but is not yet implemented. The purpose of pending tests is to facilitate a style of testing in which documentation of behavior is sketched out before tests are written to verify that behavior (and often, the before the behavior of the system being tested is itself implemented). Such sketches form a kind of specification of what tests and functionality to implement later.
To support this style of testing, a test can be given a name that specifies one bit of behavior required by the system being tested. The test can also include some code that sends more information about the behavior to the reporter when the tests run. At the end of the test, it can call method
pending, which will cause it to complete abruptly withTestPendingException. Because tests in ScalaTest can be designated as pending withTestPendingException, both the test name and any information sent to the reporter when running the test can appear in the report of a test run. (In other words, the code of a pending test is executed just like any other test.) However, because the test completes abruptly withTestPendingException, the test will be reported as pending, to indicate the actual test, and possibly the functionality it is intended to test, has not yet been implemented.Note: This method always completes abruptly with a
TestPendingException. Thus it always has a side effect. Methods with side effects are usually invoked with parentheses, as inpending(). This method is defined as a parameterless method, in flagrant contradiction to recommended Scala style, because it forms a kind of DSL for pending tests. It enables tests in suites such asFunSuiteorFunSpecto be denoted by placing "(pending)" after the test name, as in:test("that style rules are not laws") (pending)Readers of the code see "pending" in parentheses, which looks like a little note attached to the test name to indicate it is pending. Whereas "
(pending())looks more like a method call, "(pending)" lets readers stay at a higher level, forgetting how it is implemented and just focusing on the intent of the programmer who wrote the code. - def pendingUntilFixed(f: => Unit)(implicit pos: Position): Assertion with PendingStatement
Execute the passed block of code, and if it completes abruptly, throw
TestPendingException, else throwTestFailedException.Execute the passed block of code, and if it completes abruptly, throw
TestPendingException, else throwTestFailedException.This method can be used to temporarily change a failing test into a pending test in such a way that it will automatically turn back into a failing test once the problem originally causing the test to fail has been fixed. At that point, you need only remove the
pendingUntilFixedcall. In other words, apendingUntilFixedsurrounding a block of code that isn't broken is treated as a test failure. The motivation for this behavior is to encourage people to removependingUntilFixedcalls when there are no longer needed.This method facilitates a style of testing in which tests are written before the code they test. Sometimes you may encounter a test failure that requires more functionality than you want to tackle without writing more tests. In this case you can mark the bit of test code causing the failure with
pendingUntilFixed. You can then write more tests and functionality that eventually will get your production code to a point where the original test won't fail anymore. At this point the code block marked withpendingUntilFixedwill no longer throw an exception (because the problem has been fixed). This will in turn causependingUntilFixedto throwTestFailedExceptionwith a detail message explaining you need to go back and remove thependingUntilFixedcall as the problem orginally causing your test code to fail has been fixed.- f
a block of code, which if it completes abruptly, should trigger a
TestPendingException
- Exceptions thrown
TestPendingExceptionif the passed block of code completes abruptly with anExceptionorAssertionError
- final val succeed: Assertion
The
Succeededsingleton.The
Succeededsingleton.You can use
succeedto solve a type error when an async test does not end in eitherFuture[Assertion]orAssertion. BecauseAssertionis a type alias forSucceeded.type, puttingsucceedat the end of a test body (or at the end of a function being used to map the final future of a test body) will solve the type error. - final def synchronized[T0](arg0: => T0): T0
- Definition Classes
- AnyRef
- def toString(): String
- Definition Classes
- AnyRef → Any
- def typeCheckedConstraint[A, B](implicit equivalenceOfA: Equivalence[A], ev: <:<[B, A]): CanEqual[A, B]
- Definition Classes
- TripleEquals → TripleEqualsSupport
- implicit def unconstrainedEquality[A, B](implicit equalityOfA: Equality[A]): CanEqual[A, B]
- Definition Classes
- TripleEquals → TripleEqualsSupport
- final def wait(): Unit
- Definition Classes
- AnyRef
- Annotations
- @throws(classOf[java.lang.InterruptedException])
- final def wait(arg0: Long, arg1: Int): Unit
- Definition Classes
- AnyRef
- Annotations
- @throws(classOf[java.lang.InterruptedException])
- final def wait(arg0: Long): Unit
- Definition Classes
- AnyRef
- Annotations
- @throws(classOf[java.lang.InterruptedException]) @native()
- def withClue[T](clue: Any)(fun: => T): T
Executes the block of code passed as the second parameter, and, if it completes abruptly with a
ModifiableMessageexception, prepends the "clue" string passed as the first parameter to the beginning of the detail message of that thrown exception, then rethrows it.Executes the block of code passed as the second parameter, and, if it completes abruptly with a
ModifiableMessageexception, prepends the "clue" string passed as the first parameter to the beginning of the detail message of that thrown exception, then rethrows it. If clue does not end in a white space character, one space will be added between it and the existing detail message (unless the detail message is not defined).This method allows you to add more information about what went wrong that will be reported when a test fails. Here's an example:
withClue("(Employee's name was: " + employee.name + ")") { intercept[IllegalArgumentException] { employee.getTask(-1) } }
If an invocation of
interceptcompleted abruptly with an exception, the resulting message would be something like:(Employee's name was Bob Jones) Expected IllegalArgumentException to be thrown, but no exception was thrown
- Exceptions thrown
NullArgumentExceptionif the passedclueisnull
Deprecated Value Members
- def conversionCheckedConstraint[A, B](implicit equivalenceOfA: Equivalence[A], cnv: (B) => A): CanEqual[A, B]
- Definition Classes
- TripleEquals → TripleEqualsSupport
- Annotations
- @deprecated
- Deprecated
(Since version 3.1.0) The conversionCheckedConstraint method has been deprecated and will be removed in a future version of ScalaTest. It is no longer needed now that the deprecation period of ConversionCheckedTripleEquals has expired. It will not be replaced.
- def convertEquivalenceToAToBConversionConstraint[A, B](equivalenceOfB: Equivalence[B])(implicit ev: (A) => B): CanEqual[A, B]
- Definition Classes
- TripleEquals → TripleEqualsSupport
- Annotations
- @deprecated
- Deprecated
(Since version 3.1.0) The convertEquivalenceToAToBConversionConstraint method has been deprecated and will be removed in a future version of ScalaTest. It is no longer needed now that the deprecation period of ConversionCheckedTripleEquals has expired. It will not be replaced.
- def convertEquivalenceToBToAConversionConstraint[A, B](equivalenceOfA: Equivalence[A])(implicit ev: (B) => A): CanEqual[A, B]
- Definition Classes
- TripleEquals → TripleEqualsSupport
- Annotations
- @deprecated
- Deprecated
(Since version 3.1.0) The convertEquivalenceToBToAConversionConstraint method has been deprecated and will be removed in a future version of ScalaTest. It is no longer needed now that the deprecation period of ConversionCheckedTripleEquals has expired. It will not be replaced.
- def lowPriorityConversionCheckedConstraint[A, B](implicit equivalenceOfB: Equivalence[B], cnv: (A) => B): CanEqual[A, B]
- Definition Classes
- TripleEquals → TripleEqualsSupport
- Annotations
- @deprecated
- Deprecated
(Since version 3.1.0) The lowPriorityConversionCheckedConstraint method has been deprecated and will be removed in a future version of ScalaTest. It is no longer needed now that the deprecation period of ConversionCheckedTripleEquals has expired. It will not be replaced.