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.
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”.
Here are two examples of a scenario and its equivalent unit test in Java + Junit.
Given an admin user when user requests secret data then return the data [gist id=2869367]
Given an admin user and it's after office hours when user requests top secret data then return a message saying that we're closed for the day [gist id=2869548]
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.