Use the “Given/When/Then” template for unit tests for extra conceptual clarity. Modern software development emphasizes collaboration with a Customer, who is a representative for the final users of the software, and development in conjunction with automated unit tests, which ensure that the software meets the specifications intended by the customer.
Behavior Driven Development is a process that provides methods for clear communication between developers and customers. Its most elegant technique is a template for writing unit tests that bridges this gap, and makes unit tests readable by even customers, bringing them deeper into the development loop and reducing miscommunication. This format is sometimes called the “Given/When/Then” style.
The format
Unit tests should have descriptive names that explain what they do and distinguish them from other scenarios.
The assumptions, written as code that sets up preconditions for the scenario, will be first in the test. The first precondition should be described by a phrase beginning with the word “Given”, and any following preconditions should be appended with the word “and”.
The invocation under test should be described by a phrase beginning with the word “When”. There should only be one of these, since the unit test should only be testing one single operation.
The first result being tested for should be described by a phrase beginning with the word “Then”, and any following results should be explained with phrases starting with the word “and”.
Examples
Here are two examples of a scenario and its equivalent unit test in Java + Junit.
Example 1
Given an admin userwhen user requests secret datathen return the data
Example 2
Given an admin userand it's after office hourswhen user requests top secret datathen return a message saying that we're closed for the day
Applicability
This technique is ideal for pure unit tests, having only one operation under test. It is not applicable for the more comprehensive tests that simulate a conversation between a client and server, testing multiple operations.