Given When Then Pattern - anastasiamexa/Healthy-Coder-App GitHub Wiki

The "Given/When/Then" pattern is a structure commonly used in behavior-driven development (BDD) and test-driven development (TDD) to organize and describe the flow of a test case. It helps in creating clear and readable test scenarios by dividing them into three distinct parts:

1. Given:

  • Purpose: Establish the initial context or setup for the test.
  • Actions: Set up any preconditions or initial states necessary for the test.
  • Example: If you're testing a method that calculates the total price of a shopping cart, the "given" section might involve creating a shopping cart object, adding items to it, and setting up the initial prices.

2. When:

  • Purpose: Describe the specific action or event that you are testing.
  • Action: Perform the action that triggers the behavior you want to test.
  • Example: In the context of the shopping cart example, the "when" section might involve calling the method that calculates the total price.

3. Then:

  • Purpose: Define the expected outcome or result after the action or event in the "when" section.
  • Assertions: Check whether the actual result matches the expected result.
  • Example: Following the shopping cart example, the "then" section could include assertions to ensure that the calculated total price matches the expected value.

Here's a simple example in a more structured format:

@Test
void calculateTotalPrice_givenMultipleItems_whenCalculatingTotal_thenCorrectTotal() {
    // Given
    ShoppingCart cart = new ShoppingCart();
    cart.addItem(new Item("Product A", 10.0));
    cart.addItem(new Item("Product B", 15.0));

    // When
    double totalPrice = cart.calculateTotalPrice();

    // Then
    assertEquals(25.0, totalPrice);
}

In this example:

  • Given: A shopping cart with two items.
  • When: Calculating the total price of the items.
  • Then: The total price should be 25.0.

This pattern provides a clear structure for your tests, making them more readable and easier to understand. It also encourages you to think about the different aspects of your test case, such as the initial conditions, the action being performed, and the expected outcomes. This clarity is beneficial for both developers and other stakeholders involved in the testing process.