Contents

Given When Then structure with JUnit tests

Writen by: David Vlijmincx

Introduction

The given when then structure is an approach to divide your tests into three different parts. In this quick tutorial, I am going to show you how to structure a test using this approach and what the benefits are.

How to use Given When Then in tests

The idea behind the Given When Then structure is to split your tests up the three different parts.

  • Given: Inside the Given part you create and set up the state of the instances that you will use inside your tests.
  • When: Inside the When part you perform the action/behavior that should alter some state.
  • Then: The Then section is used to verify that the action had the effect that you wanted.

When trying out this approach placing Given When Then as comments inside a test might help you to create a clear separation between each part. When I write unit tests I always start with this little template to help me.

1
2
3
4
5
6
7
8
@Test
void nameOfYourTest(){
    // Given
    
    // When
    
    // Then    
}

Placing the comments helps you out when you first start using this approach.

Example of JUnit with Given When Then

I created the following example to give you an idea of what a JUnit test would look like if you use this approach.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
@Test
void changeNameOfTheDog(){
  // Given
  Dog myDog = new Dog("Max");

  // When
  myDog.changeName("Rex");

  // Then
  Assertions.assertEquals("Rex", myDog.getName());
}

Conclusion

In this quick article, I showed you how to use the given when then structure inside your unit tests. The structure helps with the readability of your testing code as it separates the three different parts of your test. If your tests need to reset some state or delete something created during the test you can add a Teardown part after the Then part to teardown what was created during the test.