This class is part of the ScalaTest matchers DSL.
This class is part of the ScalaTest matchers DSL.
This class is part of the ScalaTest matchers DSL.
Helper class used by code generated by the assert
macro.
Class used via an implicit conversion to enable two objects to be compared with
===
and !==
with a Boolean
result and an enforced type constraint between
two object types.
This class is part of the ScalaUtils “explicitly DSL”.”“
This class is part of the ScalaUtils “explicitly DSL”.”“
This class is part of the ScalaUtils “explicitly DSL”.”“
This class is part of the ScalaUtils “explicitly DSL”.”“
Class used via an implicit conversion to enable any two objects to be compared with
===
and !==
with a Boolean
result and no enforced type constraint between
two object types.
This class is part of the ScalaTest matchers DSL.
This class is part of the ScalaTest matchers DSL.
Class used via an implicit conversion to enable any two objects to be compared with
===
and !==
with an Option[String]
result and an enforced type constraint between
two object types.
Class used via an implicit conversion to enable any two objects to be compared with
===
and !==
with an Option[String]
result and no enforced type constraint between
two object types.
Wrapper class with a +-
method that, given a Numeric
argument, returns a Spread
.
This class is part of the ScalaTest matchers DSL.
This class is part of the ScalaTest matchers DSL.
This class is part of the ScalaTest matchers DSL.
This class is part of the ScalaTest matchers DSL.
This class is part of the ScalaTest matchers DSL.
This class is part of the ScalaTest matchers DSL.
This class is part of the ScalaTest matchers DSL.
This class is part of the ScalaTest matchers DSL.
This class is part of the ScalaTest matchers DSL.
This class is part of the ScalaTest matchers DSL.
This class is part of the ScalaTest matchers DSL.
This class is part of the ScalaTest matchers DSL.
This class is part of the ScalaTest matchers DSL.
This class is part of the ScalaTest matchers DSL.
This class is part of the ScalaTest matchers DSL.
This class is part of the ScalaTest matchers DSL.
This class is part of the ScalaTest matchers DSL.
This class is part of the ScalaTest matchers DSL.
This class is part of the ScalaTest matchers DSL.
This class is part of the ScalaTest matchers DSL.
This class is part of the ScalaTest matchers DSL.
This class supports the syntax of FlatSpec
, WordSpec
, fixture.FlatSpec
,
and fixture.WordSpec
.
This class is part of the ScalaUtils “explicitly DSL”.”“
This class is part of the ScalaTest matchers DSL.
This class is part of the ScalaTest matchers DSL.
Returns a TripleEqualsInvocationOnSpread[T]
, given an Spread[T]
, to facilitate
the “<left> should !== (<pivot> +- <tolerance>)
”
syntax of Matchers
.”“
Returns a TripleEqualsInvocationOnSpread[T]
, given an Spread[T]
, to facilitate
the “<left> should !== (<pivot> +- <tolerance>)
”
syntax of Matchers
.
the Spread[T]
against which to compare the left-hand value
a TripleEqualsInvocationOnSpread
wrapping the passed Spread[T]
value, with
expectingEqual
set to false
.
Returns a TripleEqualsInvocation[Null]
, given a null
reference, to facilitate
the “<left> should !== null
” syntax
of Matchers
.”“
Returns a TripleEqualsInvocation[Null]
, given a null
reference, to facilitate
the “<left> should !== null
” syntax
of Matchers
.
a null reference
a TripleEqualsInvocation
wrapping the passed null
value, with expectingEqual
set to false
.
Returns a TripleEqualsInvocation[T]
, given an object of type T
, to facilitate
the “<left> should !== <right>
” syntax
of Matchers
.”“
Returns a TripleEqualsInvocation[T]
, given an object of type T
, to facilitate
the “<left> should !== <right>
” syntax
of Matchers
.
the right-hand side value for an equality assertion
a TripleEqualsInvocation
wrapping the passed right value, with expectingEqual
set to false
.
This method enables the following syntax:
This method enables the following syntax:
num should (not be < (10) and not be > (17)) ^
This method enables the following syntax:
This method enables the following syntax:
num should (not be <= (10) and not be > (17)) ^
Returns a TripleEqualsInvocationOnSpread[T]
, given an Spread[T]
, to facilitate
the “<left> should === (<pivot> +- <tolerance>)
”
syntax of Matchers
.”“
Returns a TripleEqualsInvocationOnSpread[T]
, given an Spread[T]
, to facilitate
the “<left> should === (<pivot> +- <tolerance>)
”
syntax of Matchers
.
the Spread[T]
against which to compare the left-hand value
a TripleEqualsInvocationOnSpread
wrapping the passed Spread[T]
value, with
expectingEqual
set to true
.
Returns a TripleEqualsInvocation[Null]
, given a null
reference, to facilitate
the “<left> should === null
” syntax
of Matchers
.”“
Returns a TripleEqualsInvocation[Null]
, given a null
reference, to facilitate
the “<left> should === null
” syntax
of Matchers
.
a null reference
a TripleEqualsInvocation
wrapping the passed null
value, with expectingEqual
set to true
.
Returns a TripleEqualsInvocation[T]
, given an object of type T
, to facilitate
the “<left> should === <right>
” syntax
of Matchers
.”“
Returns a TripleEqualsInvocation[T]
, given an object of type T
, to facilitate
the “<left> should === <right>
” syntax
of Matchers
.
the right-hand side value for an equality assertion
a TripleEqualsInvocation
wrapping the passed right value, with expectingEqual
set to true
.
This method enables the following syntax:
This method enables the following syntax:
num should (not be > (10) and not be < (7)) ^
This method enables the following syntax:
This method enables the following syntax:
num should (not be >= (10) and not be < (7)) ^
This method enables the following syntax:
This method enables the following syntax:
a [RuntimeException] should be thrownBy { ... }
^
This field enables the following syntax:
This field enables the following syntax:
badBook should not be a ('goodRead)
^
This field enables syntax such as the following:
This field enables syntax such as the following:
result should equal ("hello") (after being lowerCased)
^
This method enables the following syntax for String
:
This method enables the following syntax for String
:
all(str) should fullymatch regex ("Hel*o world".r)
^
This method enables the following syntax for java.util.Map
:
This method enables the following syntax for java.util.Map
:
all(jmap) should fullymatch regex ("Hel*o world".r)
^
This method enables the following syntax:
This method enables the following syntax:
all(xs) should fullymatch regex ("Hel*o world".r)
^
This method enables the following syntax:
This method enables the following syntax:
List(1, 2, 3) should contain (allOf(1, 2)) ^
This method enables the following syntax:
This method enables the following syntax:
an [Exception] should be thrownBy { ... }
^
This field enables the following syntax:
This field enables the following syntax:
badBook should not be an (excellentRead) ^
Assert that a boolean condition, described in String
message
, is true.
Assert that a boolean condition, described in String
message
, is true.
If the condition is true
, this method returns normally.
Else, it throws TestFailedException
with the
String
obtained by invoking toString
on the
specified clue
as the exception's detail message.
the boolean condition to assert
An objects whose toString
method returns a message to include in a failure report.
if message
is null
.
if the condition is false
.
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 throws TestFailedException
.
This method is implemented in terms of a Scala macro that will generate a more helpful error message for simple quality checks of this form:
Any other form of expression will just get a plain-old TestFailedException
at this time. 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 returns Boolean
, not Option[String]
to be
the default in tests. This makes ===
consistent between tests and production code. If you have pre-existing
code you wrote under ScalaTest 1.x, in which you are expecting===
to return an Option[String]
,
use can get that behavior back by mixing in trait LegacyTripleEquals
.
the boolean condition to assert
if the condition is false
.
Assert that the value passed as expected
equals the value passed as actual
.
Assert that the value passed as expected
equals the value passed as actual
.
If the actual
value equals the expected
value
(as determined by ==
), assertResult
returns
normally. Else, assertResult
throws a
TestFailedException
whose detail message includes the expected and actual values.
the expected value
the actual value, which should equal the passed expected
value
if the passed actual
value does not equal the passed expected
value.
Assert that the value passed as expected
equals the value passed as actual
.
Assert that the value passed as expected
equals the value passed as actual
.
If the actual
equals the expected
(as determined by ==
), assertResult
returns
normally. Else, if actual
is not equal to expected
, assertResult
throws a
TestFailedException
whose detail message includes the expected and actual values, as well as the String
obtained by invoking toString
on the passed clue
.
the expected value
An object whose toString
method returns a message to include in a failure report.
the actual value, which should equal the passed expected
value
if the passed actual
value does not equal the passed expected
value.
Asserts that a given string snippet of code does not pass the Scala type checker.
Asserts that a given string snippet of code does not pass the Scala 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 Assertions
trait includes the following syntax for that purpose:
assertTypeError("val a: String = 1")
Although assertTypeError
is 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.
the snippet of code that should not type check
Helper instance used by code generated by macro assertion.
Helper instance used by code generated by macro assertion.
Assume that a boolean condition, described in String
message
, is true.
Assume that a boolean condition, described in String
message
, is true.
If the condition is true
, this method returns normally.
Else, it throws TestCanceledException
with the
String
obtained by invoking toString
on the
specified clue
as the exception's detail message.
the boolean condition to assume
An objects whose toString
method returns a message to include in a failure report.
if message
is null
.
if the condition is false
.
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 throws TestCanceledException
.
This method is implemented in terms of a Scala macro that will generate a more helpful error message for simple quality checks of this form:
Any other form of expression will just get a plain-old TestCanceledException
at this time. 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 returns Boolean
, not Option[String]
to be
the default in tests. This makes ===
consistent between tests and production code. If you have pre-existing
code you wrote under ScalaTest 1.x, in which you are expecting===
to return an Option[String]
,
use can get that behavior back by mixing in trait LegacyTripleEquals
.
the boolean condition to assume
if the condition is false
.
This method enables the following syntax for String
:
This method enables the following syntax for String
:
atLeast(1, str) should fullymatch regex ("Hel*o world".r) ^
This method enables the following syntax for java.util.Map
:
This method enables the following syntax for java.util.Map
:
atLeast(1, jmap) should fullymatch regex ("Hel*o world".r) ^
This method enables the following syntax:
This method enables the following syntax:
atLeast(1, xs) should fullymatch regex ("Hel*o world".r) ^
This method enables the following syntax:
This method enables the following syntax:
List(1, 2, 3) should contain (atLeastOneOf(1, 2)) ^
This method enables the following syntax for String
:
This method enables the following syntax for String
:
atMost(3, str) should fullymatch regex ("Hel*o world".r) ^
This method enables the following syntax for java.util.Map
:
This method enables the following syntax for java.util.Map
:
atMost(3, jmap) should fullymatch regex ("Hel*o world".r) ^
This method enables the following syntax:
This method enables the following syntax:
atMost(3, xs) should fullymatch regex ("Hel*o world".r) ^
This method enables the following syntax:
This method enables the following syntax:
List(1, 2, 3) should contain (atMostOneOf(1, 2)) ^
This field enables syntax such as the following:
This field enables syntax such as the following:
obj should (be theSameInstanceAs (string) and be theSameInstanceAs (string)) ^
This method enables the following syntax for String
:
This method enables the following syntax for String
:
between(1, 3, str) should fullymatch regex ("Hel*o world".r) ^
This method enables the following syntax for java.util.Map
:
This method enables the following syntax for java.util.Map
:
between(1, 3, jmap) should fullymatch regex ("Hel*o world".r) ^
This method enables the following syntax:
This method enables the following syntax:
between(1, 3, xs) should fullymatch regex ("Hel*o world".r) ^
Throws TestCanceledException
, with the passed
Throwable
cause, to indicate a test failed.
Throws TestCanceledException
, with the passed
Throwable
cause, to indicate a test failed.
The getMessage
method of the thrown TestCanceledException
will return cause.toString
.
a Throwable
that indicates the cause of the cancellation.
if cause
is null
Throws TestCanceledException
, with the passed
String
message
as the exception's detail
message and Throwable
cause, to indicate a test failed.
Throws TestCanceledException
, with the passed
String
message
as the exception's detail
message and Throwable
cause, to indicate a test failed.
A message describing the failure.
A Throwable
that indicates the cause of the failure.
if message
or cause
is null
Throws TestCanceledException
, with the passed
String
message
as the exception's detail
message, to indicate a test was canceled.
Throws TestCanceledException
, with the passed
String
message
as the exception's detail
message, to indicate a test was canceled.
A message describing the cancellation.
if message
is null
Throws TestCanceledException
to indicate a test was canceled.
Throws TestCanceledException
to indicate a test was canceled.
This field enables the following syntax:
This field enables the following syntax:
"val a: String = 1" shouldNot compile
^
This field enables syntax such as the following:
This field enables syntax such as the following:
list should (contain ('a') and have length (7)) ^
Provides a Constraint[A, B]
class for any two types A
and B
, enforcing the type constraint that B
is
implicitly convertible to A
, given an implicit Equivalence[A]
.
Provides a Constraint[A, B]
class for any two types A
and B
, enforcing the type constraint that B
is
implicitly convertible to A
, given an implicit Equivalence[A]
.
The returned Constraint
's areEqual
method uses the implicitly passed Equivalence[A]
's
areEquivalent
method to determine equality.
This method is overridden and made implicit by subtraits
ConversionCheckedTripleEquals
) and
ConversionCheckedLegacyTripleEquals
, and
overriden as non-implicit by the other subtraits in this package.
an Equivalence[A]
type class to which the Constraint.areEqual
method will delegate to determine equality.
an implicit conversion from B
to A
a Constraint[A, B]
whose areEqual
method delegates to the areEquivalent
method of
the passed Equivalence[A]
.
Provides a Constraint[A, B]
for any two types A
and B
, enforcing the type constraint
that A
must be a subtype of B
, given an explicit Equivalence[B]
.
Provides a Constraint[A, B]
for any two types A
and B
, enforcing the type constraint
that A
must be a subtype of B
, given an explicit Equivalence[B]
.
This method is used to enable the Explicitly
DSL for
TypeCheckedTripleEquals
by requiring an explicit Equivalance[B]
, but
taking an implicit function that provides evidence that A
is a subtype of B.
The returned Constraint
's areEqual
method uses the implicitly passed Equivalence[B]
's
areEquivalent
method to determine equality.
This method is overridden and made implicit by subtraits
LowPriorityTypeCheckedConstraint
(extended by
TypeCheckedTripleEquals
), and
LowPriorityTypeCheckedLegacyConstraint
(extended by
TypeCheckedLegacyTripleEquals
), and
overriden as non-implicit by the other subtraits in this package.
an Equivalence[B]
type class to which the Constraint.areEqual
method
will delegate to determine equality.
evidence that A
is a subype of B
a Constraint[A, B]
whose areEqual
method delegates to the
areEquivalent
method of the passed Equivalence[B]
.
Provides a Constraint[A, B]
class for any two types A
and B
, enforcing the type constraint that A
is
implicitly convertible to B
, given an explicit Equivalence[B]
.
Provides a Constraint[A, B]
class for any two types A
and B
, enforcing the type constraint that A
is
implicitly convertible to B
, given an explicit Equivalence[B]
.
This method is used to enable the Explicitly
DSL for
ConversionCheckedTripleEquals
by requiring an explicit Equivalance[B]
, but
taking an implicit function that converts from A
to B.
The returned Constraint
's areEqual
method uses the implicitly passed Equivalence[B]
's
areEquivalent
method to determine equality.
This method is overridden and made implicit by subtraits
LowPriorityConversionCheckedConstraint
(extended by
ConversionCheckedTripleEquals
), and
LowPriorityConversionCheckedLegacyConstraint
(extended by
ConversionCheckedLegacyTripleEquals
), and
overriden as non-implicit by the other subtraits in this package.
a Constraint[A, B]
whose areEqual
method delegates to the areEquivalent
method of
the passed Equivalence[B]
.
Provides a Constraint[A, B]
for any two types A
and B
, enforcing the type constraint
that B
must be a subtype of A
, given an explicit Equivalence[A]
.
Provides a Constraint[A, B]
for any two types A
and B
, enforcing the type constraint
that B
must be a subtype of A
, given an explicit Equivalence[A]
.
This method is used to enable the Explicitly
DSL for
TypeCheckedTripleEquals
by requiring an explicit Equivalance[B]
, but
taking an implicit function that provides evidence that A
is a subtype of B. For example, under TypeCheckedTripleEquals
,
this method (as an implicit method), would be used to compile this statement:
def closeEnoughTo1(num: Double): Boolean = (num === 1.0)(decided by forgivingEquality)
The returned Constraint
's areEqual
method uses the implicitly passed Equivalence[A]
's
areEquivalent
method to determine equality.
This method is overridden and made implicit by subtraits
TypeCheckedTripleEquals
) and
TypeCheckedLegacyTripleEquals
, and
overriden as non-implicit by the other subtraits in this package.
evidence that B
is a subype of A
a Constraint[A, B]
whose areEqual
method delegates to the areEquivalent
method of
the passed Equivalence[A]
.
Provides a Constraint[A, B]
class for any two types A
and B
, enforcing the type constraint that B
is
implicitly convertible to A
, given an explicit Equivalence[A]
.
Provides a Constraint[A, B]
class for any two types A
and B
, enforcing the type constraint that B
is
implicitly convertible to A
, given an explicit Equivalence[A]
.
This method is used to enable the Explicitly
DSL for
ConversionCheckedTripleEquals
by requiring an explicit Equivalance[A]
, but
taking an implicit function that converts from B
to A. For example, under ConversionCheckedTripleEquals
,
this method (as an implicit method), would be used to compile this statement:
def closeEnoughTo1(num: Double): Boolean = (num === 1.0)(decided by forgivingEquality)
The returned Constraint
's areEqual
method uses the implicitly passed Equivalence[A]
's
areEquivalent
method to determine equality.
This method is overridden and made implicit by subtraits
ConversionCheckedTripleEquals
) and
ConversionCheckedLegacyTripleEquals
, and
overriden as non-implicit by the other subtraits in this package.
an Equivalence[A]
type class to which the Constraint.areEqual
method will delegate to determine equality.
a Constraint[A, B]
whose areEqual
method delegates to the areEquivalent
method of
the passed Equivalence[A]
.
Implicitly converts an object of a Numeric
type to a PlusOrMinusWrapper
,
to enable a +-
method to be invoked on that object.
Implicitly converts an object of a Numeric
type to a PlusOrMinusWrapper
,
to enable a +-
method to be invoked on that object.
This implicit conversion method converts a Symbol
to a
HavePropertyMatcherGenerator
, to enable the symbol to be used with the have ('author ("Dickens"))
syntax.
Implicitly converts an object of type T
to a AnyShouldWrapper[T]
,
to enable should
methods to be invokable on that object.
Converts to an CheckingEqualizer
that provides ===
and !==
operators
that result in Boolean
and enforce a type constraint.
Converts to an CheckingEqualizer
that provides ===
and !==
operators
that result in Boolean
and enforce a type constraint.
This method is overridden and made implicit by subtraits TypeCheckedTripleEquals
and
ConversionCheckedTripleEquals
, and overriden as
non-implicit by the other subtraits in this package.
the object whose type to convert to CheckingEqualizer
.
if left
is null
.
Converts to an Equalizer
that provides ===
and !==
operators that
result in Boolean
and enforce no type constraint.
Converts to an Equalizer
that provides ===
and !==
operators that
result in Boolean
and enforce no type constraint.
This method is overridden and made implicit by subtrait TripleEquals
and overriden as non-implicit by the other
subtraits in this package.
the object whose type to convert to Equalizer
.
if left
is null
.
Converts to a LegacyCheckingEqualizer
that provides ===
and !==
operators
that result in Option[String]
and enforce a type constraint.
Converts to a LegacyCheckingEqualizer
that provides ===
and !==
operators
that result in Option[String]
and enforce a type constraint.
This method is overridden and made implicit by subtraits TypeCheckedLegacyTripleEquals
and ConversionCheckedLegacyTripleEquals
, and
overriden as non-implicit by the other subtraits in this package.
the object whose type to convert to LegacyCheckingEqualizer
.
if left
is null
.
Converts to a LegacyEqualizer
that provides ===
and !==
operators that
result in Option[String]
and enforce no type constraint.
Converts to a LegacyEqualizer
that provides ===
and !==
operators that
result in Option[String]
and enforce no type constraint.
This method is overridden and made implicit by subtrait LegacyTripleEquals
and overriden as non-implicit
by the other subtraits in this package.
the object whose type to convert to LegacyEqualizer
.
if left
is null
.
Implicitly converts an object of type scala.util.matching.Regex
to a RegexWrapper
,
to enable withGroup
and withGroups
methods to be invokable on that object.
Implicitly converts an object of type java.lang.String
to a StringShouldWrapper
,
to enable should
methods to be invokable on that object.
Implicitly converts an object of type java.lang.String
to a StringShouldWrapper
,
to enable should
methods to be invokable on that object.
This field enables syntax such as the following:
This field enables syntax such as the following:
result should equal ("hello") (decided by defaultEquality)
^
Returns an Equality[A]
for any type A
that determines equality
by first calling .deep
on any Array
(on either the left or right side),
then comparing the resulting objects with ==
.
Returns an Equality[A]
for any type A
that determines equality
by first calling .deep
on any Array
(on either the left or right side),
then comparing the resulting objects with ==
.
a default Equality
for type A
This field enables the following syntax:
This field enables the following syntax:
seq should be (defined) ^
This method enables the following syntax:
This method enables the following syntax:
list should (not be definedAt (7) and not be definedAt (9)) ^
This field enables syntax such as the following, given an
Equivalence[String]
named myStringEquivalence
:
This field enables syntax such as the following, given an
Equivalence[String]
named myStringEquivalence
:
result should equal ("hello") (determined by myStringEquivalence)
^
This field enables the following syntax:
This field enables the following syntax:
list should be (empty) ^
This field enables syntax such as the following:
This field enables syntax such as the following:
string should (endWith ("ago") and include ("score")) ^
This method enables syntax such as the following:
This method enables syntax such as the following:
result should equal (null)
^
This method enables syntax such as the following:
This method enables syntax such as the following:
result should equal (100 +- 1) ^
This method enables the following syntax:
This method enables the following syntax:
result should equal (7)
^
The left should equal (right)
syntax works by calling ==
on the left
value, passing in the right
value, on every type except arrays. If both left
and right are arrays, deep
will be invoked on both left
and right
before comparing them with ==. Thus, even though this expression
will yield false, because Array
's equals
method compares object identity:
Array(1, 2) == Array(1, 2) // yields false
The following expression will not result in a TestFailedException
, because ScalaTest will compare
the two arrays structurally, taking into consideration the equality of the array's contents:
Array(1, 2) should equal (Array(1, 2)) // succeeds (i.e., does not throw TestFailedException)
If you ever do want to verify that two arrays are actually the same object (have the same identity), you can use the
be theSameInstanceAs
syntax.
This method enables the following syntax for String
:
This method enables the following syntax for String
:
every(str) should fullymatch regex ("Hel*o world".r)
^
This method enables the following syntax for java.util.Map
:
This method enables the following syntax for java.util.Map
:
every(jmap) should fullymatch regex ("Hel*o world".r)
^
This method enables the following syntax:
This method enables the following syntax:
every(xs) should fullymatch regex ("Hel*o world".r)
^
This method enables the following syntax for String
:
This method enables the following syntax for String
:
exactly(str) should fullymatch regex ("Hel*o world".r)
^
This method enables the following syntax for java.util.Map
:
This method enables the following syntax for java.util.Map
:
exactly(jmap) should fullymatch regex ("Hel*o world".r)
^
This method enables the following syntax:
This method enables the following syntax:
exactly(xs) should fullymatch regex ("Hel*o world".r)
^
This field enables the following syntax:
This field enables the following syntax:
file should exist ^
Throws TestFailedException
, with the passed
Throwable
cause, to indicate a test failed.
Throws TestFailedException
, with the passed
Throwable
cause, to indicate a test failed.
The getMessage
method of the thrown TestFailedException
will return cause.toString
.
a Throwable
that indicates the cause of the failure.
if cause
is null
Throws TestFailedException
, with the passed
String
message
as the exception's detail
message and Throwable
cause, to indicate a test failed.
Throws TestFailedException
, with the passed
String
message
as the exception's detail
message and Throwable
cause, to indicate a test failed.
A message describing the failure.
A Throwable
that indicates the cause of the failure.
if message
or cause
is null
Throws TestFailedException
, with the passed
String
message
as the exception's detail
message, to indicate a test failed.
Throws TestFailedException
, with the passed
String
message
as the exception's detail
message, to indicate a test failed.
A message describing the failure.
if message
is null
Throws TestFailedException
to indicate a test failed.
Throws TestFailedException
to indicate a test failed.
This field enables syntax such as the following:
This field enables syntax such as the following:
string should (fullyMatch regex ("Hel*o, wor.d") and not have length (99)) ^
This field enables syntax such as the following:
This field enables syntax such as the following:
list should (have length (3) and not contain ('a')) ^
This method enables the following syntax:
This method enables the following syntax:
List(1, 2, 3) should contain (inOrder(1, 2)) ^
This method enables the following syntax:
This method enables the following syntax:
List(1, 2, 3) should contain (inOrderOnly(1, 2)) ^
This field enables syntax such as the following:
This field enables syntax such as the following:
string should (include ("hope") and not startWith ("no")) ^
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 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 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 as String
,
for example), this method will complete abruptly with a TestFailedException
.
the function value that should throw the expected exception
an implicit Manifest
representing the type of the specified
type parameter.
the intercepted exception, if it is of the expected type
if the passed function does not complete abruptly with an exception
that's an instance of the specified type
passed expected
value.
This field enables the following syntax:
This field enables the following syntax:
map should not contain key (10)
^
This field enables the following syntax:
This field enables the following syntax:
"hi" should not have length (3) ^
Provides a Constraint[A, B]
class for any two types A
and B
, enforcing the type constraint that A
is
implicitly convertible to B
, given an implicit Equivalence[B]
.
Provides a Constraint[A, B]
class for any two types A
and B
, enforcing the type constraint that A
is
implicitly convertible to B
, given an implicit Equivalence[B]
.
The returned Constraint
's areEqual
method uses the implicitly passed Equivalence[B]
's
areEquivalent
method to determine equality.
This method is overridden and made implicit by subtraits
LowPriorityConversionCheckedConstraint
(extended by
ConversionCheckedTripleEquals
), and
LowPriorityConversionCheckedLegacyConstraint
(extended by
ConversionCheckedLegacyTripleEquals
), and
overriden as non-implicit by the other subtraits in this package.
an implicit conversion from A
to B
a Constraint[A, B]
whose areEqual
method delegates to the areEquivalent
method of
the passed Equivalence[B]
.
Provides a Constraint[A, B]
for any two types A
and B
, enforcing the type constraint
that A
must be a subtype of B
, given an implicit Equivalence[B]
.
Provides a Constraint[A, B]
for any two types A
and B
, enforcing the type constraint
that A
must be a subtype of B
, given an implicit Equivalence[B]
.
The returned Constraint
's areEqual
method uses the implicitly passed Equivalence[A]
's
areEquivalent
method to determine equality.
This method is overridden and made implicit by subtraits
LowPriorityTypeCheckedConstraint
(extended by
TypeCheckedTripleEquals
), and
LowPriorityTypeCheckedLegacyConstraint
(extended by
TypeCheckedLegacyTripleEquals
), and
overriden as non-implicit by the other subtraits in this package.
an Equivalence[B]
type class to which the Constraint.areEqual
method
will delegate to determine equality.
evidence that A
is a subype of B
a Constraint[A, B]
whose areEqual
method delegates to the
areEquivalent
method of the passed Equivalence[B]
.
This method enables the following syntax:
This method enables the following syntax:
exception should not have message ("file not found")
^
This method enables the following syntax for String
:
This method enables the following syntax for String
:
no(str) should fullymatch regex ("Hel*o world".r)
^
This method enables the following syntax for java.util.Map
:
This method enables the following syntax for java.util.Map
:
no(jmap) should fullymatch regex ("Hel*o world".r)
^
This method enables the following syntax:
This method enables the following syntax:
no(xs) should fullymatch regex ("Hel*o world".r)
^
This field enables the following syntax:
This field enables the following syntax:
noException should be thrownBy ^
This method enables the following syntax:
This method enables the following syntax:
List(1, 2, 3) should contain (noneOf(1, 2)) ^
This field enables syntax like the following:
This field enables syntax like the following:
myFile should (not be an (directory) and not have ('name ("foo.bar"))) ^
This method enables syntax such as the following:
This method enables syntax such as the following:
book should have (message ("A TALE OF TWO CITIES") (of [Book]), title ("A Tale of Two Cities")) ^
This method enables the following syntax:
This method enables the following syntax:
List(1, 2, 3) should contain (oneOf(1, 2)) ^
This method enables the following syntax:
This method enables the following syntax:
List(1, 2, 3) should contain (only(1, 2)) ^
This method enables the following syntax:
This method enables the following syntax:
evaluating { "hi".charAt(-1) } should produce [StringIndexOutOfBoundsException] ^
This field enables the following syntax:
This field enables the following syntax:
file should be (readable) ^
This field enables the following syntax:
This field enables the following syntax:
"eight" should not fullyMatch regex ("""(-)?(\d+)(\.\d*)?""".r) ^
This field enables the following syntax:
This field enables the following syntax:
set should not have size (3)
^
This field enables the following syntax:
This field enables the following syntax:
seq should be (sorted) ^
This field enables syntax such as the following:
This field enables syntax such as the following:
string should (startWith ("Four") and include ("year")) ^
This method enables the following syntax:
This method enables the following syntax:
the [FileNotFoundException] should be thrownBy { ... }
^
This method enables the following syntax:
This method enables the following syntax:
List(1, 2, 3) should contain (theSameElementsAs(List(1, 2, 3))) ^
This method enables the following syntax:
This method enables the following syntax:
List(1, 2, 3) should contain (theSameElementsInOrderAs(List(1, 2))) ^
This field enables the following syntax:
This field enables the following syntax:
oneString should not be theSameInstanceAs (anotherString) ^
This method enables the following syntax:
This method enables the following syntax:
a [RuntimeException] should be thrownBy {...}
^
Trap and return any thrown exception that would normally cause a ScalaTest test to fail, or create and return a new RuntimeException
indicating no exception is thrown.
Trap and return any thrown exception that would normally cause a ScalaTest test to fail, or create and return a new RuntimeException
indicating no exception is thrown.
This method is intended to be used in the Scala interpreter to eliminate large stack traces when trying out ScalaTest assertions and
matcher expressions. It is not intended to be used in regular test code. If you want to ensure that a bit of code throws an expected
exception, use intercept
, not trap
. Here's an example interpreter session without trap
:
scala> import org.scalatest._ import org.scalatest._scala> import Matchers._ import Matchers._
scala> val x = 12 a: Int = 12
scala> x shouldEqual 13 org.scalatest.exceptions.TestFailedException: 12 did not equal 13 at org.scalatest.Assertions$class.newAssertionFailedException(Assertions.scala:449) at org.scalatest.Assertions$.newAssertionFailedException(Assertions.scala:1203) at org.scalatest.Assertions$AssertionsHelper.macroAssertTrue(Assertions.scala:417) at .<init>(<console>:15) at .<clinit>(<console>) at .<init>(<console>:7) at .<clinit>(<console>) at $print(<console>) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at scala.tools.nsc.interpreter.IMain$ReadEvalPrint.call(IMain.scala:731) at scala.tools.nsc.interpreter.IMain$Request.loadAndRun(IMain.scala:980) at scala.tools.nsc.interpreter.IMain.loadAndRunReq$1(IMain.scala:570) at scala.tools.nsc.interpreter.IMain.interpret(IMain.scala:601) at scala.tools.nsc.interpreter.IMain.interpret(IMain.scala:565) at scala.tools.nsc.interpreter.ILoop.reallyInterpret$1(ILoop.scala:745) at scala.tools.nsc.interpreter.ILoop.interpretStartingWith(ILoop.scala:790) at scala.tools.nsc.interpreter.ILoop.command(ILoop.scala:702) at scala.tools.nsc.interpreter.ILoop.processLine$1(ILoop.scala:566) at scala.tools.nsc.interpreter.ILoop.innerLoop$1(ILoop.scala:573) at scala.tools.nsc.interpreter.ILoop.loop(ILoop.scala:576) at scala.tools.nsc.interpreter.ILoop$$anonfun$process$1.apply$mcZ$sp(ILoop.scala:867) at scala.tools.nsc.interpreter.ILoop$$anonfun$process$1.apply(ILoop.scala:822) at scala.tools.nsc.interpreter.ILoop$$anonfun$process$1.apply(ILoop.scala:822) at scala.tools.nsc.util.ScalaClassLoader$.savingContextLoader(ScalaClassLoader.scala:135) at scala.tools.nsc.interpreter.ILoop.process(ILoop.scala:822) at scala.tools.nsc.MainGenericRunner.runTarget$1(MainGenericRunner.scala:83) at scala.tools.nsc.MainGenericRunner.process(MainGenericRunner.scala:96) at scala.tools.nsc.MainGenericRunner$.main(MainGenericRunner.scala:105) at scala.tools.nsc.MainGenericRunner.main(MainGenericRunner.scala)
That's a pretty tall stack trace. Here's what it looks like when you use trap
:
scala> trap { x shouldEqual 13 } res1: Throwable = org.scalatest.exceptions.TestFailedException: 12 did not equal 13
Much less clutter. Bear in mind, however, that if no exception is thrown by the
passed block of code, the trap
method will create a new NormalResult
(a subclass of Throwable
made for this purpose only) and return that. If the result was the Unit
value, it
will simply say that no exception was thrown:
scala> trap { x shouldEqual 12 } res2: Throwable = No exception was thrown.
If the passed block of code results in a value other than Unit
, the NormalResult
's toString
will print the value:
scala> trap { "Dude!" } res3: Throwable = No exception was thrown. Instead, result was: "Dude!"
Although you can access the result value from the NormalResult
, its type is Any
and therefore not
very convenient to use. It is not intended that trap
be used in test code. The sole intended use case for trap
is decluttering
Scala interpreter sessions by eliminating stack traces when executing assertion and matcher expressions.
Provides a Constraint[A, B]
for any two types A
and B
, enforcing the type constraint
that B
must be a subtype of A
, given an implicit Equivalence[A]
.
Provides a Constraint[A, B]
for any two types A
and B
, enforcing the type constraint
that B
must be a subtype of A
, given an implicit Equivalence[A]
.
The returned Constraint
's areEqual
method uses the implicitly passed Equivalence[A]
's
areEquivalent
method to determine equality.
This method is overridden and made implicit by subtraits
TypeCheckedTripleEquals
) and
TypeCheckedLegacyTripleEquals
, and
overriden as non-implicit by the other subtraits in this package.
evidence that B
is a subype of A
a Constraint[A, B]
whose areEqual
method delegates to the areEquivalent
method of
the passed Equivalence[A]
.
Provides a Constraint[A, B]
class for any two types A
and B
, with no type constraint enforced, given an
implicit Equality[A]
.
Provides a Constraint[A, B]
class for any two types A
and B
, with no type constraint enforced, given an
implicit Equality[A]
.
The returned Constraint
's areEqual
method uses the implicitly passed Equality[A]
's
areEqual
method to determine equality.
This method is overridden and made implicit by subtraits TripleEquals
and
LegacyTripleEquals
, and
overriden as non-implicit by the other subtraits in this package.
an Equality[A]
type class to which the Constraint.areEqual
method will delegate to determine equality.
a Constraint[A, B]
whose areEqual
method delegates to the areEqual
method of
the passed Equality[A]
.
This field enables the following syntax:
This field enables the following syntax:
map should not contain value (10)
^
Executes the block of code passed as the second parameter, and, if it
completes abruptly with a ModifiableMessage
exception,
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 ModifiableMessage
exception,
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 intercept
completed 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
if the passed clue
is null
This field enables the following syntax:
This field enables the following syntax:
file should be (writable) ^
Assert that an Option[String]
is None
.
Assert that an Option[String]
is None
.
If the condition is None
, this method returns normally.
Else, it throws TestFailedException
with the String
value of the Some
included in the TestFailedException
'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
.
the Option[String]
to assert
This method has been deprecated in favor of macro assertion and will be removed in a future version of ScalaTest. If you need this, please copy the source code into your own trait instead.
if the Option[String]
is Some
.
Assert that an Option[String]
is None
.
Assert that an Option[String]
is None
.
If the condition is None
, this method returns normally.
Else, it throws TestFailedException
with the String
value of the Some
, as well as the
String
obtained by invoking toString
on the
specified clue
,
included in the TestFailedException
'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
.
the Option[String]
to assert
An object whose toString
method returns a message to include in a failure report.
This method has been deprecated in favor of macro assertion and will be removed in a future version of ScalaTest. If you need this, please copy the source code into your own trait instead.
if message
is null
.
if the Option[String]
is Some
.
Assume that an Option[String]
is None
.
Assume that an Option[String]
is None
.
If the condition is None
, this method returns normally.
Else, it throws TestCanceledException
with the String
value of the Some
included in the TestCanceledException
's
detail message.
This form of assume
is usually called in conjunction with an
implicit conversion to Equalizer
, using a ===
comparison, as in:
assume(a === b)
For more information on how this mechanism works, see the documentation for
Equalizer
.
the Option[String]
to assert
This method has been deprecated in favor of macro assumption and will be removed in a future version of ScalaTest. If you need this, please copy the source code into your own trait instead.
if the Option[String]
is Some
.
Assume that an Option[String]
is None
.
Assume that an Option[String]
is None
.
If the condition is None
, this method returns normally.
Else, it throws TestCanceledException
with the String
value of the Some
, as well as the
String
obtained by invoking toString
on the
specified clue
,
included in the TestCanceledException
's detail message.
This form of assume
is usually called in conjunction with an
implicit conversion to Equalizer
, using a ===
comparison, as in:
assume(a === b, "extra info reported if assertion fails")
For more information on how this mechanism works, see the documentation for
Equalizer
.
the Option[String]
to assert
An object whose toString
method returns a message to include in a failure report.
This method has been deprecated in favor of macro assumption and will be removed in a future version of ScalaTest. If you need this, please copy the source code into your own trait instead.
if message
is null
.
if the Option[String]
is Some
.
The evaluating { ... } should produce [...Exception]
syntax has been deprecated and
will be removed in a future version of ScalaTest. Please use a/an [...Exception] should be
thrownBy { ... }
instead.
The evaluating { ... } should produce [...Exception]
syntax has been deprecated and
will be removed in a future version of ScalaTest. Please use a/an [...Exception] should be
thrownBy { ... }
instead.
This method enables syntax such as the following:
evaluating { "hi".charAt(-1) } should produce [StringIndexOutOfBoundsException] ^
Please use 'an [Exception] should be thrownBy { ... }' syntax instead
This expect
method has been deprecated; Please use assertResult
instead.
This expect
method has been deprecated; Please use assertResult
instead.
To get rid of the deprecation warning, simply replace expect
with
assertResult
. The name expect
will be used for a different purposes in
a future version of ScalaTest.
This expect method has been deprecated. Please replace all invocations of expect with an identical invocation of assertResult instead.
This expect
method has been deprecated; Please use assertResult
instead.
This expect
method has been deprecated; Please use assertResult
instead.
To get rid of the deprecation warning, simply replace expect
with
assertResult
. The name expect
will be used for a different purposes in
a future version of ScalaTest.
This expect method has been deprecated. Please replace all invocations of expect with an identical invocation of assertResult instead.
This expectResult
method has been deprecated; Please use assertResult
instead.
This expectResult
method has been deprecated; Please use assertResult
instead.
To get rid of the deprecation warning, simply replace expectResult
with
assertResult
. The name expectResult
will be used for a different purposes in
a future version of ScalaTest.
This expectResult method has been deprecated. Please replace all invocations of expectResult with an identical invocation of assertResult instead.
This expectResult
method has been deprecated; Please use assertResult
instead.
This expectResult
method has been deprecated; Please use assertResult
instead.
To get rid of the deprecation warning, simply replace expectResult
with
assertResult
. The name expectResult
will be used for a different purposes in
a future version of ScalaTest.
This expectResult method has been deprecated. Please replace all invocations of expectResult with an identical invocation of assertResult instead.
Trait that provides a domain specific language (DSL) for expressing assertions in tests using the word
should
.For example, if you mix
Matchers
into a suite class, you can write an equality assertion in that suite like this:result should equal (3)
Here
result
is a variable, and can be of any type. If the object is anInt
with the value 3, execution will continue (i.e., the expression will result in the unit value,()
). Otherwise, aTestFailedException
will be thrown with a detail message that explains the problem, such as"7 did not equal 3"
. ThisTestFailedException
will cause the test to fail.Here is a table of contents for this documentation:
Boolean
properties withbe
BeMatchers
String
s andArray
s as collectionsand
andor
Option
shave
length
andsize
withHavePropertyMatcher
sMatchers migration in ScalaTest 2.0 and 2.1.0
Deprecations
Prior to 2.0, ScalaTest's matchers DSL was provided by traits
org.scalatest.matchers.ShouldMatchers
andorg.scalatest.matchers.MustMatchers
. These are now deprecated in favor of traits in packageorg.scalatest
. The fully qualified name of the originalShouldMatchers
is noworg.scalatest.Matchers
, and the fully qualified name of the originalMustMatchers
is noworg.scalatest.MustMatchers
. The old fully qualified names will continue to work during a lengthy deprecation cycle, but will generate a deprecation warning and eventually be removed in a future version of ScalaTest. You can migrate existing uses ofShouldMatchers
by simply importing or mixing inorg.scalatest.Matchers
instead oforg.scalatest.matchers.ShouldMatchers
, and can migrate existing uses oforg.scalatest.matchers.MustMatchers
by importing or mixing inorg.scalatest.MustMatchers
instead oforg.scalatest.matchers.MustMatchers
.Two other deprecations in ScalaTest 2.0 matchers are
be
===
<value>
andevaluating
...
should
produce
syntax. This will both continue to work as before, but will generate a deprecation warning and eventually be removed in a future version of ScalaTest. thebe
===
syntax is being deprecated so that all uses of===
in ScalaTest consistently provide the new features of tunable type checking, tolerance support, and customized equality. Please replace uses of this syntax with one of the other ways to check equality described in the next section. Theeventually
syntax is being deprecated because it is replaced bythrownBy
clauses, as described below.Potential breakages
Although ScalaTest's matchers have undergone a major refactor in 2.0, all previously documented syntax for matchers should continue to work exactly the same with one potential exception, which should in practice be extremely rare. The potential breakage is that if you included
length
orsize
along with custom have-property matchers that you wrote, you'll get a compiler error. To fix such an error, add after yourlength
orsize
invocation an(of [<type>])
clause, as described below.The only other source of potential breakage is the fragile base class problem. We have added fields and methods to
Matchers
in 2.0 that may conflict with fields and methods in your existing classes and cause a compiler error. Such issues can usually be easily fixed locally with simple renames or refactors, but if you prefer to subtract a token fromMatchers
, you can do so by mixing together your ownMatchers
trait from component traits, as described below. Note that you should not see any new implicit conflicts, because we managed to reduce the number of implicits brought into scope by 2.0 matchers compared to 1.x by about 75%.Checking equality with matchers
ScalaTest matchers provides five different ways to check equality, each designed to address a different need. They are:
The “
left
should
equal
(right)
” syntax requires anorg.scalautils.Equality[L]
to be provided (either implicitly or explicitly), whereL
is the left-hand type on whichshould
is invoked. In the "left
should
equal
(right)
" case, for example,L
is the type ofleft
. Thus ifleft
is typeInt
, the "left
should
equal
(right)
" statement would require anEquality[Int]
.By default, an implicit
Equality[T]
instance is available for any typeT
, in which equality is implemented by simply invoking==
on theleft
value, passing in theright
value, with special treatment for arrays. If eitherleft
orright
is an array,deep
will be invoked on it before comparing with ==. Thus, the following expression will yield false, becauseArray
'sequals
method compares object identity:The next expression will by default not result in a
TestFailedException
, because defaultEquality[Array[Int]]
compares the two arrays structurally, taking into consideration the equality of the array's contents:If you ever do want to verify that two arrays are actually the same object (have the same identity), you can use the
be theSameInstanceAs
syntax, described below.You can customize the meaning of equality for a type when using "
should
equal
," "should
===
," orshouldEqual
syntax by defining implicitEquality
instances that will be used instead of defaultEquality
. You might do this to normalize types before comparing them with==
, for instance, or to avoid calling the==
method entirely, such as if you want to compareDouble
s with a tolerance. For an example, see the main documentation of traitEquality
.You can always supply implicit parameters explicitly, but in the case of implicit parameters of type
Equality[T]
, ScalaUtils provides a simple "explictly" DSL. For example, here's how you could explicitly supply anEquality[String]
instance that normalizes both left and right sides (which must be strings), by transforming them to lowercase:The
after
being
lowerCased
expression results in anEquality[String]
, which is then passed explicitly as the second curried parameter toequal
. For more information on the explictly DSL, see the main documentation for traitExplicitly
.The "
should
be
" andshouldBe
syntax do not take anEquality[T]
and can therefore not be customized. They always use the default approach to equality described above. As a result, "should
be
" andshouldBe
will likely be the fastest-compiling matcher syntax for equality comparisons, since the compiler need not search for an implicitEquality[T]
each time.The
should
===
syntax (and its complement,should
!==
) can be used to enforce type constraints at compile-time between the left and right sides of the equality comparison. Here's an example:By default, the "
Some(2)
should
===
(2)
" statement would fail at runtime. By mixing in the equality constraints provided byTypeCheckedTripleEquals
, however, the statement fails to compile. For more information and examples, see the main documentation for traitTypeCheckedTripleEquals
.Checking size and length
You can check the size or length of any type of object for which it makes sense. Here's how checking for length looks:
result should have length 3
Size is similar:
result should have size 10
The
length
syntax can be used withString
,Array
, anyscala.collection.GenSeq
, anyjava.util.List
, and any typeT
for which an implicitLength[T]
type class is available in scope. Similarly, thesize
syntax can be used withArray
, anyscala.collection.GenTraversable
, anyjava.util.Collection
, anyjava.util.Map
, and any typeT
for which an implicitSize[T]
type class is available in scope. You can enable thelength
orsize
syntax for your own arbitrary types, therefore, by definingLength
orSize
type classes for those types.In addition, the
length
syntax can be used with any object that has a field or method namedlength
or a method namedgetLength
. Similarly, thesize
syntax can be used with any object that has a field or method namedsize
or a method namedgetSize
. The type of alength
orsize
field, or return type of a method, must be eitherInt
orLong
. Any such method must take no parameters. (The Scala compiler will ensure at compile time that the object on whichshould
is being invoked has the appropriate structure.)Checking strings
You can check for whether a string starts with, ends with, or includes a substring like this:
You can check for whether a string starts with, ends with, or includes a regular expression, like this:
And you can check whether a string fully matches a regular expression, like this:
string should fullyMatch regex """(-)?(\d+)(\.\d*)?"""
The regular expression passed following the
regex
token can be either aString
or ascala.util.matching.Regex
.With the
startWith
,endWith
,include
, andfullyMatch
tokens can also be used with an optional specification of required groups, like this:You can check whether a string is empty with
empty
:You can also use most of ScalaTest's matcher syntax for collections on
String
by treating theString
s as collections of characters. For examples, see theString
s andArray
s as collections section below.Greater and less than
You can check whether any type for which an implicit
Ordering[T]
is available is greater than, less than, greater than or equal, or less than or equal to a value of typeT
. The syntax is:Checking
Boolean
properties withbe
If an object has a method that takes no parameters and returns boolean, you can check it by placing a
Symbol
(afterbe
) that specifies the name of the method (excluding an optional prefix of "is
"). A symbol literal in Scala begins with a tick mark and ends at the first non-identifier character. Thus,'traversableAgain
results in aSymbol
object at runtime, as does'completed
and'file
. Here's an example:iter shouldBe 'traversableAgain
Given this code, ScalaTest will use reflection to look on the object referenced from
emptySet
for a method that takes no parameters and results inBoolean
, with either the nameempty
orisEmpty
. If found, it will invoke that method. If the method returnstrue
, execution will continue. But if it returnsfalse
, aTestFailedException
will be thrown that will contain a detail message, such as:This
be
syntax can be used with any reference (AnyRef
) type. If the object does not have an appropriately named predicate method, you'll get aTestFailedException
at runtime with a detailed message that explains the problem. (For the details on how a field or method is selected during this process, see the documentation forBeWord
.)If you think it reads better, you can optionally put
a
oran
afterbe
. For example,java.io.File
has two predicate methods,isFile
andisDirectory
. Thus with aFile
object namedtemp
, you could write:temp should be a 'file
Or, given
java.awt.event.KeyEvent
has a methodisActionKey
that takes no arguments and returnsBoolean
, you could assert that aKeyEvent
is an action key with:keyEvent should be an 'actionKey
If you prefer to check
Boolean
properties in a type-safe manner, you can use aBePropertyMatcher
. This would allow you to write expressions such as:These expressions would fail to compile if
should
is used on an inappropriate type, as determined by the type parameter of theBePropertyMatcher
being used. (For example,file
in this example would likely be of typeBePropertyMatcher[java.io.File]
. If used with an appropriate type, such an expression will compile and at run time theBoolean
property method or field will be accessed directly; i.e., no reflection will be used. See the documentation forBePropertyMatcher
for more information.Using custom
BeMatchers
If you want to create a new way of using
be
, which doesn't map to an actual property on the type you care about, you can create aBeMatcher
. You could use this, for example, to createBeMatcher[Int]
calledodd
, which would match any oddInt
, andeven
, which would match any evenInt
. Given this pair ofBeMatcher
s, you could check whether anInt
was odd or even with expressions like:For more information, see the documentation for
BeMatcher
.Checking object identity
If you need to check that two references refer to the exact same object, you can write:
Checking an object's class
If you need to check that an object is an instance of a particular class or trait, you can supply the type to “
be
a
” or “be
an
”:Because type parameters are erased on the JVM, we recommend you insert an underscore for any type parameters when using this syntax. Both of the following test only that the result is an instance of
List[_]
, because at runtime the type parameter has been erased:Checking numbers against a range
Often you may want to check whether a number is within a range. You can do that using the
+-
operator, like this:Any of these expressions will cause a
TestFailedException
to be thrown if the floating point value,sevenDotOh
is outside the range6.7
to7.1
. You can use+-
with any typeT
for which an implicitNumeric[T]
exists, such as integral types:Checking for emptiness
You can check whether an object is "empty", like this:
The
empty
token can be used with any typeL
for which an implicitEmptiness[L]
exists. TheEmptiness
companion object provides implicits forGenTraversable[E]
,java.util.Collection[E]
,java.util.Map[K, V]
,String
,Array[E]
, andOption[E]
. In addition, theEmptiness
companion object provides structural implicits for types that declare anisEmpty
method that returns aBoolean
. Here are some examples:Working with "containers"
You can check whether a collection contains a particular element like this:
traversable should contain ("five")
The
contain
syntax shown above can be used with any typeC
that has a "containing" nature, evidenced by an implicitorg.scalatest.enablers.Containing[L]
, whereL
is left-hand type on whichshould
is invoked. In theContaining
companion object, implicits are provided for typesGenTraversable[E]
,java.util.Collection[E]
,java.util.Map[K, V]
,String
,Array[E]
, andOption[E]
. Here are some examples:ScalaTest's implicit methods that provide the
Containing[L]
type classes require anEquality[E]
, whereE
is an element type. For example, to obtain aContaining[Array[Int]]
you must supply anEquality[Int]
, either implicitly or explicitly. Thecontain
syntax uses thisEquality[E]
to determine containership. Thus if you want to change how containership is determined for an element typeE
, place an implicitEquality[E]
in scope or use the explicitly DSL. Although the implicit parameter required for thecontain
syntax is of typeContaining[L]
, implicit conversions are provided in theContaining
companion object fromEquality[E]
to the various types of containers ofE
. Here's an example:Note that when you use the explicitly DSL with
contain
you need to wrap the entirecontain
expression in parentheses, as shown here.In addition to determining whether an object contains another object, you can use
contain
to make other determinations. For example, thecontain
oneOf
syntax ensures that one and only one of the specified elements are contained in the containing object:Note that if multiple specified elements appear in the containing object,
oneOf
will fail:If you really want to ensure one or more of the specified elements are contained in the containing object, use
atLeastOneOf
, described below, instead ofoneOf
. Keep in mind,oneOf
means "exactly one of."Note also that with any
contain
syntax, you can place custom implicitEquality[E]
instances in scope to customize how containership is determined, or use the explicitly DSL. Here's an example:The
contain
noneOf
syntax does the opposite ofoneOf
: it ensures none of the specified elements are contained in the containing object:Working with "aggregations"
As mentioned, the "
contain
," "contain
oneOf
," and "contain
noneOf
" syntax requires aContaining[L]
be provided, whereL
is the left-hand type. Othercontain
syntax, which will be described in this section, requires anAggregating[L]
be provided, where againL
is the left-hand type. (AnAggregating[L]
instance defines the "aggregating nature" of a typeL
.) The reason, essentially, is thatcontain
syntax that makes sense forOption
is enabled byContaining[L]
, whereas syntax that does not make sense forOption
is enabled byAggregating[L]
. For example, it doesn't make sense to assert that anOption[Int]
contains all of a set of integers, as it could only ever contain one of them. But this does make sense for a type such asList[Int]
that can aggregate zero to many integers.The
Aggregating
companion object provides implicit instances ofAggregating[L]
for typesGenTraversable[E]
,java.util.Collection[E]
,java.util.Map[K, V]
,String
,Array[E]
. Note that these are the same types as are supported withContaining
, but withOption[E]
missing. Here are some examples:The
contain
atLeastOneOf
syntax, for example, works for any typeL
for which anAggregating[L]
exists. It ensures that at least one of (i.e., one or more of) the specified objects are contained in the containing object:Similar to
Containing[L]
, the implicit methods that provide theAggregating[L]
instances require anEquality[E]
, whereE
is an element type. For example, to obtain aAggregating[Vector[String]]
you must supply anEquality[String]
, either implicitly or explicitly. Thecontain
syntax uses thisEquality[E]
to determine containership. Thus if you want to change how containership is determined for an element typeE
, place an implicitEquality[E]
in scope or use the explicitly DSL. Although the implicit parameter required for thecontain
syntax is of typeAggregating[L]
, implicit conversions are provided in theAggregating
companion object fromEquality[E]
to the various types of aggregations ofE
. Here's an example:The "
contain
atMostOneOf
" syntax lets you specify a set of objects at most one of which should be contained in the containing object:The "
contain
allOf
" syntax lets you specify a set of objects that should all be contained in the containing object:The "
contain
only
" syntax lets you assert that the containing object contains only the specified objects, though it may contain more than one of each:The "
contain
theSameElementsAs
" and "contain
theSameElementsInOrderAs
syntax differ from the others in that the right hand side is aGenTraversable[_]
rather than a varargs ofAny
. (Note: in a future 2.0 milestone release, possibly 2.0.M6, these will likely be widened to accept any typeR
for which anAggregating[R]
exists.)The "
contain
theSameElementsAs
" syntax lets you assert that two aggregations contain the same objects:The number of times any family of equal objects appears must also be the same in both the left and right aggregations. The specified objects may appear multiple times, but must appear in the order they appear in the right-hand list. For example, if the last 3 element is left out of the right-hand list in the previous example, the expression would fail because the left side has three 3's and the right hand side has only two:
Working with "sequences"
The rest of the
contain
syntax, which will be described in this section, requires aSequencing[L]
be provided, where againL
is the left-hand type. (ASequencing[L]
instance defines the "sequencing nature" of a typeL
.) The reason, essentially, is thatcontain
syntax that implies an "order" of elements makes sense only for types that place elements in a sequence. For example, it doesn't make sense to assert that aMap[String, Int]
orSet[Int]
contains all of a set of integers in a particular order, as these types don't necessarily define an order for their elements. But this does make sense for a type such asSeq[Int]
that does define an order for its elements.The
Sequencing
companion object provides implicit instances ofSequencing[L]
for typesGenSeq[E]
,java.util.List[E]
,String
, andArray[E]
. Here are some examples:Similar to
Containing[L]
, the implicit methods that provide theAggregating[L]
instances require anEquality[E]
, whereE
is an element type. For example, to obtain aAggregating[Vector[String]]
you must supply anEquality[String]
, either implicitly or explicitly. Thecontain
syntax uses thisEquality[E]
to determine containership. Thus if you want to change how containership is determined for an element typeE
, place an implicitEquality[E]
in scope or use the explicitly DSL. Although the implicit parameter required for thecontain
syntax is of typeAggregating[L]
, implicit conversions are provided in theAggregating
companion object fromEquality[E]
to the various types of aggregations ofE
. Here's an example:The "
contain
inOrderOnly
" syntax lets you assert that the containing object contains only the specified objects, in order. The specified objects may appear multiple times, but must appear in the order they appear in the right-hand list. Here's an example:The "
contain
inOrder
" syntax lets you assert that the containing object contains only the specified objects in order, likeinOrderOnly
, but allows other objects to appear in the left-hand aggregation as well: contain more than one of each:Note that "order" in
inOrder
,inOrderOnly
, andtheSameElementsInOrderAs
(described below) in theAggregation[L]
instances built-in to ScalaTest is defined as "iteration order".Lastly, the "
contain
theSameElementsInOrderAs
" syntax lets you assert that two aggregations contain the same exact elements in the same (iteration) order:The previous assertion succeeds because the iteration order of a
TreeSet
is the natural ordering of its elements, which in this case is 1, 2, 3. An iterator obtained from the left-handList
will produce the same elements in the same order.Working with "sortables"
You can also ask whether the elements of "sortable" objects (such as
Array
s, JavaList
s, andGenSeq
s) are in sorted order, like this:Working with iterators
Althought it seems desireable to provide similar matcher syntax for Scala and Java iterators to that provided for sequences like
Seq
s,Array
, andjava.util.List
, the ephemeral nature of iterators makes this problematic. Some syntax (such asshould
contain
) is relatively straightforward to support on iterators, but other syntax (such as, for example,Inspector
expressions on nested iterators) is not. Rather than allowing inconsistencies between sequences and iterators in the API, we chose to not support any such syntax directly on iterators:Instead, you will need to convert your iterators to a sequence explicitly before using them in matcher expressions:
scala> it.toStream should contain (2)
We recommend you convert (Scala or Java) iterators to
Stream
s, as shown in the previous example, so that you can continue to reap any potential benefits provided by the laziness of the underlying iterator.Inspector shorthands
You can use the
Inspectors
syntax with matchers as well as assertions. If you have a multi-dimensional collection, such as a list of lists, usingInspectors
is your best option:For assertions on one-dimensional collections, however, matchers provides "inspector shorthands." Instead of writing:
You can write:
all (xs) should be < 10
The previous statement asserts that all elements of the
xs
list should be less than 10. All of the inspectors have shorthands in matchers. Here is the full list:all
- succeeds if the assertion holds true for every elementatLeast
- succeeds if the assertion holds true for at least the specified number of elementsatMost
- succeeds if the assertion holds true for at most the specified number of elementsbetween
- succeeds if the assertion holds true for between the specified minimum and maximum number of elements, inclusiveevery
- same asall
, but lists all failing elements if it fails (whereasall
just reports the first failing element)exactly
- succeeds if the assertion holds true for exactly the specified number of elementsHere are some examples:
Like
Inspectors
, objects used with inspector shorthands can be any typeT
for which aCollecting[T, E]
is availabe, which by default includesGenTraversable
, JavaCollection
, JavaMap
,Array
s, andString
s. Here are some examples:Single-element collections
To assert both that a collection contains just one "lone" element as well as something else about that element, you can use the
loneElement
syntax provided by traitLoneElement
. For example, if aSet[Int]
should contain just one element, anInt
less than or equal to 10, you could write:You can invoke
loneElement
on any typeT
for which an implicitCollecting[E, T]
is available, whereE
is the element type returned by theloneElement
invocation. By default, you can useloneElement
onGenTraversable
, JavaCollection
, JavaMap
,Array
, andString
.Java collections and maps
You can use similar syntax on Java collections (
java.util.Collection
) and maps (java.util.Map
). For example, you can check whether a JavaCollection
orMap
isempty
, like this:Even though Java's
List
type doesn't actually have alength
orgetLength
method, you can nevertheless check the length of a JavaList
(java.util.List
) like this:javaList should have length 9
You can check the size of any Java
Collection
orMap
, like this:In addition, you can check whether a Java
Collection
contains a particular element, like this:javaCollection should contain ("five")
One difference to note between the syntax supported on Java and Scala collections is that in Java,
Map
is not a subtype ofCollection
, and does not actually define an element type. You can ask a JavaMap
for an "entry set" via theentrySet
method, which will return theMap
's key/value pairs wrapped in a set ofjava.util.Map.Entry
, but aMap
is not actually a collection ofEntry
. To make JavaMap
s easier to work with, however, ScalaTest matchers allows you to treat a JavaMap
as a collection ofEntry
, and defines a convenience implementation ofjava.util.Map.Entry
inorg.scalatest.Entry
. Here's how you use it:You can you alse just check whether a Java
Map
contains a particular key, or value, like this:String
s andArray
s as collectionsYou can also use all the syntax described above for Scala and Java collections on
Array
s andString
s. Here are some examples:be
as an equality comparisonAll uses of
be
other than those shown previously perform an equality comparison. They work the same asequal
when it is used with default equality. This redundancy betweenbe
andequals
exists in part because it enables syntax that sometimes sounds more natural. For example, instead of writing:result should equal (null)
You can write:
result should be (null)
(Hopefully you won't write that too much given
null
is error prone, andOption
is usually a better, well, option.) As mentioned previously, the other difference betweenequal
andbe
is thatequal
delegates the equality check to anEquality
typeclass, whereasbe
always uses default equality. Here are some other examples ofbe
used for equality comparison:As with
equal
used with default equality, usingbe
on arrays results indeep
being called on both arrays prior to callingequal
. As a result, the following expression would not throw aTestFailedException
:Because
be
is used in several ways in ScalaTest matcher syntax, just as it is used in many ways in English, one potential point of confusion in the event of a failure is determining whetherbe
was being used as an equality comparison or in some other way, such as a property assertion. To make it more obvious whenbe
is being used for equality, the failure messages generated for those equality checks will include the wordequal
in them. For example, if this expression fails with aTestFailedException
:The detail message in that
TestFailedException
will include the words"equal to"
to signifybe
was in this case being used for equality comparison:Being negative
If you wish to check the opposite of some condition, you can simply insert
not
in the expression. Here are a few examples:Checking that a snippet of code 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
Matchers
trait includes the following syntax for that purpose:"val a: String = 1" shouldNot compile
Although this syntax is implemented with a macro that determines at compile time whether the snippet of code represented by the string type checks, errors (i.e., snippets of code that do type check) are reported as test failures at runtime.
Logical expressions with
and
andor
You can also combine matcher expressions with
and
and/oror
, however, you must place parentheses or curly braces around theand
oror
expression. For example, thisand
-expression would not compile, because the parentheses are missing:Instead, you need to write:
Here are some more examples:
Two differences exist between expressions composed of these
and
andor
operators and the expressions you can write on regularBoolean
s using its&&
and||
operators. First, expressions withand
andor
do not short-circuit. The following contrived expression, for example, would print"hello, world!"
:In other words, the entire
and
oror
expression is always evaluated, so you'll see any side effects of the right-hand side even if evaluating only the left-hand side is enough to determine the ultimate result of the larger expression. Failure messages produced by these expressions will "short-circuit," however, mentioning only the left-hand side if that's enough to determine the result of the entire expression. This "short-circuiting" behavior of failure messages is intended to make it easier and quicker for you to ascertain which part of the expression caused the failure. The failure message for the previous expression, for example, would be:Most likely this lack of short-circuiting would rarely be noticeable, because evaluating the right hand side will usually not involve a side effect. One situation where it might show up, however, is if you attempt to
and
anull
check on a variable with an expression that uses the variable, like this:If
map
isnull
, the test will indeed fail, but with aNullPointerException
, not aTestFailedException
. Here, theNullPointerException
is the visible right-hand side effect. To get aTestFailedException
, you would need to check each assertion separately:If
map
isnull
in this case, thenull
check in the first expression will fail with aTestFailedException
, and the second expression will never be executed.The other difference with
Boolean
operators is that although&&
has a higher precedence than||
,and
andor
have the same precedence. Thus although theBoolean
expression(a || b && c)
will evaluate the&&
expression before the||
expression, like(a || (b && c))
, the following expression:Will evaluate left to right, as:
If you really want the
and
part to be evaluated first, you'll need to put in parentheses, like this:Working with
Option
sScalaTest matchers has no special support for
Option
s, but you can work with them quite easily using syntax shown previously. For example, if you wish to check whether an option isNone
, you can write any of:If you wish to check an option is defined, and holds a specific value, you can write either of:
If you only wish to check that an option is defined, but don't care what it's value is, you can write:
If you mix in (or import the members of)
OptionValues
, you can write one statement that indicates you believe an option should be defined and then say something else about its value. Here's an example:Checking arbitrary properties with
have
Using
have
, you can check properties of any type, where a property is an attribute of any object that can be retrieved either by a public field, method, or JavaBean-styleget
oris
method, like this:This expression will use reflection to ensure the
title
,author
, andpubYear
properties of objectbook
are equal to the specified values. For example, it will ensure thatbook
has either a public Java field or method namedtitle
, or a public method namedgetTitle
, that when invoked (or accessed in the field case) results in a the string"Programming in Scala"
. If all specified properties exist and have their expected values, respectively, execution will continue. If one or more of the properties either does not exist, or exists but results in an unexpected value, aTestFailedException
will be thrown that explains the problem. (For the details on how a field or method is selected during this process, see the documentation forHavePropertyMatcherGenerator
.)When you use this syntax, you must place one or more property values in parentheses after
have
, seperated by commas, where a property value is a symbol indicating the name of the property followed by the expected value in parentheses. The only exceptions to this rule is the syntax for checking size and length shown previously, which does not require parentheses. If you forget and put parentheses in, however, everything will still work as you'd expect. Thus instead of writing:You can alternatively, write:
If a property has a value different from the specified expected value, a
TestFailedError
will be thrown with a detailed message that explains the problem. For example, if you assert the following on abook
whose title isMoby Dick
:You'll get a
TestFailedException
with this detail message:If you prefer to check properties in a type-safe manner, you can use a
HavePropertyMatcher
. This would allow you to write expressions such as:These expressions would fail to compile if
should
is used on an inappropriate type, as determined by the type parameter of theHavePropertyMatcher
being used. (For example,title
in this example might be of typeHavePropertyMatcher[org.publiclibrary.Book]
. If used with an appropriate type, such an expression will compile and at run time the property method or field will be accessed directly; i.e., no reflection will be used. See the documentation forHavePropertyMatcher
for more information.Using
length
andsize
withHavePropertyMatcher
sIf you want to use
length
orsize
syntax with your own customHavePropertyMatcher
s, you can do so, but you must write(of [“the type”])
afterwords. For example, you could write:Prior to ScalaTest 2.0, “
length
(22)
” yielded aHavePropertyMatcher[Any, Int]
that used reflection to dynamically look for alength
field orgetLength
method. In ScalaTest 2.0, “length
(22)
” yields aMatcherFactory1[Any, Length]
, so it is no longer aHavePropertyMatcher
. The(of [<type>])
syntax converts the theMatcherFactory1[Any, Length]
to aHavePropertyMatcher[<type>, Int]
.Using custom matchers
If none of the built-in matcher syntax (or options shown so far for extending the syntax) satisfy a particular need you have, you can create custom
Matcher
s that allow you to place your own syntax directly aftershould
. For example, classjava.io.File
has a methodisHidden
, which indicates whether a file of a certain path and name is hidden. Because theisHidden
method takes no parameters and returnsBoolean
, you can call it usingbe
with a symbol orBePropertyMatcher
, yielding assertions like:If it doesn't make sense to have your custom syntax follow
be
, you might want to create a customMatcher
instead, so your syntax can followshould
directly. For example, you might want to be able to check whether ajava.io.File
's name ends with a particular extension, like this:ScalaTest provides several mechanism to make it easy to create custom matchers, including ways to compose new matchers out of existing ones complete with new error messages. For more information about how to create custom
Matcher
s, please see the documentation for theMatcher
trait.Checking for 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. With
Matchers
mixed in, you can check for an expected exception like this:If
charAt
throws an instance ofStringIndexOutOfBoundsException
, this expression will result in that exception. But ifcharAt
completes normally, or throws a different exception, this expression will complete abruptly with aTestFailedException
.If you need to further isnpect an expected exception, you can capture it using this syntax:
This expression 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. Here's an example:
thrown.getMessage should equal ("String index out of range: -1")
If you prefer you can also capture and inspect an expected exception in one statement, like this:
You can also state that no exception should be thrown by some code, like this:
Note: the following syntax from ScalaTest 1.x has been deprecated:
Such uses will continue to work during the deprecation cycle, but support for this syntax will eventually be removed in a future version of ScalaTest. Please change all uses to a corresponding use of the syntax described previously in this section.
Those pesky parens
Perhaps the most tricky part of writing assertions using ScalaTest matchers is remembering when you need or don't need parentheses, but bearing in mind a few simple rules should help. It is also reassuring to know that if you ever leave off a set of parentheses when they are required, your code will not compile. Thus the compiler will help you remember when you need the parens. That said, the rules are:
1. Although you don't always need them, you may choose to always put parentheses around right-hand values, such as the
7
innum should equal (7)
:2. Except for
length
,size
andmessage
, you must always put parentheses around the list of one or more property values following ahave
:3. You must always put parentheses around
and
andor
expressions, as in:4. Although you don't always need them, you may choose to always put parentheses around custom
Matcher
s when they appear directly afternot
:That's it. With a bit of practice it should become natural to you, and the compiler will always be there to tell you if you forget a set of needed parentheses.
Note: ScalaTest's matchers are in part inspired by the matchers of RSpec, Hamcrest, and specs2, and its “
shouldNot compile
” syntax by theillTyped
macro of shapeless.