2011-12-03

Choice between Given, When, Then

Writing your first Stories for Behavior Driven Development (BDD) you will soon come to the point when it is about to consider if a step is Given, if it is When or if it is Then. So what’s better:

Given Application A is running
When I log in

or is it better to write:

Given Application A is running
Given I logged in

Mind that the second Given could be replaced by And. I just wanted to emphasize that it is now a Given statement.

My answer: It depends. Derived from one of my previous posts Given, When, Then – Which Tense? my conclusion is:

  • Given: Should summarize which is not actually in focus of the story but required to understand the context of the test or state of the system under test.
  • When: Describes the steps required to reach the state you want to test. If steps cannot be taken your applications behavior might have changed but your story is not necessarily broken. Thus if When statements are written with help of JUnit you should consider to user org.junit.Assume to validate the state.
  • Then: This is the state you want to test. If this fails your story is for sure broken. Thus again if you are using JUnit you would use org.junit.Assert in here.

Considering this here are the three stories which deal with log in:

Given Application A is running
When I log in as user with username N
Then I will see the UI of Application A
And I will see username N somewhere on the screen

So here the log in process is part of the steps to reach the state to test, which is to have access to the application’s UI.

Given Application A is running
And I am logged in as user N
When I change my password to password P
Then I will receive a notification email
And my credentials change to username N with password P

Thus log is only required to understand the context/state of the system. And finally:

Given Application A is running
And there is a registered user N
When the login screen appears
Then I am able to log in with valid credentials for user N

This time the log in process is in focus of the scenario we want to test.

Is this guidance of any help for you? Or do you have another pattern when to choose When, when to choose Given and when to choose Then?