Search code examples
unit-testingtestingintegration-testingbdd

Isolating Behaviour In BDDs


Suppose I have a program that does three things in succession:

  1. Task 1
  2. Task 2
  3. Task 3

Now suppose I want to write BDDs for Task 2. Let us say when it fails. Now Task 2 is performed only after Task 1 succeeds. But Task 1 itself can succeed in many ways (for instance, we my program retries Task 1 if the downstream system responds with an error for a fixed number of times). My question is, what all behaviour of Task 1 should I consider when writing tests for Task 2?

Given_Task2Fails_Task1IsRetried_Expect_SomeBehaviour

Given_Task2Fails_Task1IsNotRetried_Expect_SomeBehaviour

If this is the case, then I need create all the permutations and combinations of each of the tasks keeping Task 2 as constant. This blows up the number of scenarios with a large amount of duplicate code. This is what I mean:

Given_Task2Fails_Task1IsRetried_Task3IsNotRetried_Expect_SomeBehaviour

Given_Task2Fails_Task1IsNotRetried_Task3IsNotRetried_Expect_SomeBehaviour

Given_Task2Fails_Task1IsRetried_Task3IsRetried_Expect_SomeBehaviour

Given_Task2Fails_Task1IsNotRetried_Task3IsRetried_Expect_SomeBehaviour

How do I write solid scenarios in such cases? Ideally, I would want to vary each and every parameter of my system keeping Task 2 constant. But that's like a brute-force approach and I am pretty sure there are better approaches out there.


Solution

  • You should assume Task 1 has succeeded when writing tests for Task 2. The various ways Task 1 can fail — and recover — is not something you need to capture in tests verifying the behavior of Task 2.

    Given Task 1 succeeded
    When Task 2 is performed
    Then Outcome 2 should have happened
    

    What happens when Task 1 fails is not even a concern for tests asserting that Task 1 succeeds. In fact, the various ways Task 1 can fail could be (and possibly should be) captured as their own scenarios, unit tests or integration tests.