|
ScalaTest User Guide Writing your first test Using assertions Tagging your tests Running your tests Sharing fixtures Sharing tests Using matchers Testing with mock objects Tests as specifications Property-based testing Other goodies Philosophy and design Selecting a style |
Using assertionsScalaTest makes three assertions available by default in any style trait. You can use:
To get moving quickly in ScalaTest, learn and use these three assertions. Later if you prefer you can switch to the more expressive matchers DSL.
In any Scala program, you can write assertions by invoking val left = 2 val right = 1 assert(left == right)
If the passed expression is
ScalaTest defines another
If you pass the previous val left = 2 val right = 1 assert(left == right, left + " did not equal " + right)
Using this form of val left = 2 val right = 1 assert(left === right)
Because you use Expected resultsAlthough=== provides a natural, readable extension to Scala's assert mechanism,
as the operands become lengthy, the code becomes less readable. In addition, the === comparison
doesn't distinguish between actual and expected values. The operands are just called left and right,
because if one were named expected and the other actual, it would be difficult for people to
remember which was which. To help with these limitations of assert, ScalaTest provides a method called expect that
can be used as an alternative to assert with ===. To use expect, you place
the expected value in parentheses after expect, followed by curly braces containing code
that should result in the expected value. For example:
val a = 5 val b = 2 expect(2) { a - b }
In this case, the expected value is Intercepted exceptionsSometimes 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
To make this common use case easier to express and read, ScalaTest provides an val s = "hi" intercept[IndexOutOfBoundsException] { s.charAt(-1) }
This code behaves much like the previous example. If val s = "hi" val thrown = intercept[IndexOutOfBoundsException] { s.charAt(-1) } assert(thrown.getMessage === "String index out of range: -1") Next, learn about tagging your tests. |
ScalaTest is brought to you by Bill Venners, with
contributions from several other folks. It is sponsored by
Artima, Inc.
ScalaTest is free, open-source software
released under the Apache
2.0 license.
Copyright © 2009-2012 Artima, Inc. All Rights Reserved.