testing – Where to specify mock behavior in Given-When-then syntax?

The scenario should be set up in the Given step. This involves mocking parts of the system. However, a mock might be used in the When step when that’s part of the action.

When reading your two scenarios, they both look reasonable as natural language:

  • Given a control panel in its initial state, And an engine that will fail to start, When the start button is pressed, Then the LED will become red.
  • Given a control panel in its initial state, When the start button is pressed, And the engine fails to start, Then the LED will become red.

However, the second variant does not conform to the Given-When-Then structure.

  • Given describes the initial context of the scenario.
  • When describes actions or interaction with the system.
  • Then describes the outcome of the actions.

Both of your scenarios obfuscate the actions by using passive voice: “the button is pressed”. In my experience, it is better to name an actor who interacts with the system (third-person perspective) or to write the scenario from a first-person perspective: “When the driver presses the button” or “When I press then button”.

From this, it is clear that “the engine fails to start” is not an action – it is an outcome. But asserting that as an outcome makes no sense for the scenario that you’re trying to test. That the engine will fail to start is an essential part of the context of your scenario, so it should be specified in the Given step.

I would write your scenario as:

Scenario: the engine status LED reports a failing engine.

Given a control panel
And and a broken engine
When the driver starts the car
Then the engine fails to start
And the engine status LED lights up red.