Table of Contents
- Getting started
- First steps
- Adding Given/When/Then behavior (and ‘And’)
- More on Given, When, Then, and And
- Add more tests within ‘describe’
- Testing Option/Some/None in a BDD test
- Nesting describe blocks
- Using ‘before’ and ‘after’
- Mark tests as pending
- Temporarily disabling tests
- Testing expected exceptions
- Using matchers
- Tagging your BDD tests
- More information
This page is very much a work in progress, but it currently shows a small collection of ScalaTest BDD examples. I’ll keep adding more BDD examples as time goes on. Also, in this article I assume that you are familiar/comfortable with Scala and SBT, and are at least slightly familiar with using ScalaTest.
As I’ve written before, when I finished writing the Scala Cookbook it ended up being about 140 pages longer than my editor wanted, and I had to cut some content from the book. Unfortunately the chapter on “Logging & Testing” was one of the victims of the cut, but I’m glad to say that I’ve finally taken the time to convert that material to HTML. As a result, here are links to the 12 ScalaTest tutorials in that chapter:
Problem: You want to use a mock object framework in your ScalaTest tests, such as Mockito.
ScalaTest offers support for the following mock testing frameworks:
Because the support for each framework is similar, let’s take a look at using Mockito.
Before starting, imagine that you have a login web service for your application, and rather than call the real web service during your tests, you just want to mock one up.
Problem: When using ScalaTest, you want to temporarily disable one or more tests, presumably until you can get them working again.
When using BDD-style tests, change
it method calls to
Problem: You want a way to label your individual ScalaTest unit tests, so you can easily choose to include or exclude them when running your test suite. For instance, you may want to tag long-running tests like database or web service tests, because they take a long time to run, and you don’t want to run them all the time.
Create one or more custom tags, then include those tags in your test specifications. When you run your tests, declare which tests you want to run, or not run.
Problem: You want to make your ScalaTest unit tests more BDD-like by adding “Given/When/Then” behavior to them.
GivenWhenThen trait into your
FunSpec BDD test, then add the Given/When/Then conditions, as shown in the following code:
Problem: You want to write your ScalaTest tests using a behavior-driven development (BDD) style.
Extend the ScalaTest
FunSpec trait, typically with the
BeforeAndAfter trait. Then use the approach shown in the following
PizzaSpec test class.
A series of tests begins with the
describe method, with individual tests declared in