What is it?
The Four-Phase Test is a testing pattern which is used to structure each test with four distinct phases executed in sequence. We could easily apply it to all programming languages.
Example
I’d like to start with an example test in Ruby. Then we’ll destructure it and discuss the phases one by one.
test "should downcase email before save" do
@user = User.new(email: "maX@mustermann.com") # Setup
@user.save # Exercise
assert_equal "max@mustermann.com", @user.email # Verify
end
Phases
As you can see in the example above, the first three phases are easily noticeable.
1. Setup
As you might guess, in the Setup phase we’re setting up everything needed in order to exhibit the expected behaviour.
@user = User.new(email: "maX@mustermann.com")
2. Exercise
During this phase, the system under test is executed.
@user.save
3. Verify
Here you should verify the result of the exercise against your expectations.
assert_equal "max@mustermann.com", @user.email
4. Teardown
In this phase everything should be reverted to its initial pre-setup state. In Rails this is already done for you because the tests are running inside a database transaction.
Final notes
I personally prefer separating the different phases with newlines. This improves the readability of the tests which in turn saves you time.