Given-When-Then JUnit Test

Rich_Lee
2 min readJan 20, 2023

--

Spring Boot is a popular Java-based framework for building microservices and web applications. One important aspect of developing these applications is writing effective tests to ensure that they work as expected. In this blog, we will discuss the Given-When-Then rule for structuring tests, and how it can be used in conjunction with Spring Boot and JUnit 5.

The Given-When-Then rule is a common way to structure tests, and it is used to make tests more readable and maintainable. The basic structure of the rule is as follows:

  • Given: this section sets up the initial state of the system, including any required dependencies or data.
  • When: this section triggers the action or behavior that we want to test.
  • Then: this section asserts that the expected outcome has occurred.

Using this structure helps to clearly separate the setup, execution, and validation phases of the test, making it easier to understand what the test is doing and why it is important.

In Spring Boot, we can use JUnit 5 to write tests that follow the Given-When-Then rule. Here is an example of a test that validates a discount coupon.

@DisplayName("Discount coupon validation test")
public class DiscountCouponTest {

private DiscountCouponService service;

@BeforeEach
public void setup() {
service = new DiscountCouponService();
}

@Test
public void testValidCoupon() {
// Given
String couponCode = "SPRINGBOOT";

// When
boolean isValid = service.validateCoupon(couponCode);

// Then
assertTrue(isValid);
}

@Test
public void testInvalidCoupon() {
// Given
String couponCode = "INVALID";

// When
boolean isValid = service.validateCoupon(couponCode);

// Then
assertFalse(isValid);
}
}

In this example, we have a test class called DiscountCouponTest which is using @DisplayName annotation to give a display name to the test class. The class has two test methods: testValidCoupon and testInvalidCoupon. Each method follows the Given-When-Then structure, setting up the initial state of the system, triggering the action, and asserting that the expected outcome has occurred.

In the first test method testValidCoupon, we are passing a valid coupon code "SPRINGBOOT" and in the second test method testInvalidCoupon, we are passing an invalid coupon code "INVALID".

This is just a basic example of how you can use the Given-When-Then rule to structure your tests in Spring Boot. By following this structure, you can make your tests more readable and maintainable, which will make it easier to catch bugs and ensure that your applications are working as expected.

--

--

Rich_Lee

- Founder, FelixAI LLC - SF bay area, CA - Software Engineer Fellowship @Formation