The BDD style of writing tests is to write given/when/then steps. These broadly fall into the categories of pre-condition, action, check also known as prepare/act/assert.
The critical thing about the given/when/then is that they’re largely supposed to talk about the expectations of the system in a requirement and behavioural language.
You might express these steps in the name of a unit test. Example –
Alternatively you might put the given/when and then in comments, avoiding the cruft of just writing
// given on its own. Say it if you mean it, but don’t just type it.
Some test frameworks like to add labels to the tests, which is cute, though I’m not sure how useful it is.
Some test tools, like
RestAssured use the naming in their fluent function calls – e.g.
Is Given a Given?
The advice below might equally apply to when, though perhaps less to then, since a test without an assertable thing is not really a full test.
The difficulty people seem to face, in feature files, test names and other things that like to talk about the given of the situation is what to do when there’s nothing much to say.
Given the system is up and running When I log in Then I am logged in
What are we trying to prove with the given here? It’s a kind of empty given.
I’ve even seen
RestAssured code like this –
given().when().get("/bar").then().statusCode(200). Given what? Given the computer is on?
You can drop the given. Indeed, if your assertions are about the state of the system when you don’t take an action on it – e.g. when it’s empty or just being there – then you don’t need a when either.
Dropping The Cruft
- No special pre-condition – don’t mention given in the name of the test or any steps
- No special action – don’t mention a when
- thenTheAnswerIsCorrect – don’t mention a then in a name or comment that has nothing to say other than isCorrect.