How do you create a simple unit test with JUnit in Spring Boot?

Table of Contents

Introduction

Unit testing is a crucial part of ensuring that individual components in your Spring Boot application behave as expected. JUnit is the most commonly used framework for writing unit tests in Java applications, including Spring Boot. Writing simple unit tests allows you to test business logic in isolation, ensuring that each part of your application performs as intended. In this guide, we'll walk you through creating a simple unit test with JUnit 5 in Spring Boot.

Steps to Create a Simple Unit Test with JUnit in Spring Boot

1. Set Up Dependencies

Before you begin writing tests, ensure that you have the necessary dependencies in your pom.xml file for JUnit and Spring Boot's testing tools.

Add the following dependency for JUnit 5 and Spring Boot's testing features:

The spring-boot-starter-test includes JUnit 5 (along with other useful libraries like Mockito and Hamcrest) to facilitate writing unit tests.

2. Create a Service to Test

For this example, let’s create a simple service class that we will test. This service provides basic functionality like calculating a product's price after applying a discount.

Here, ProductService has a method calculateDiscountedPrice() that calculates the discounted price of a product based on the original price and discount percentage.

3. Write the Unit Test

Now, let’s write a unit test for the ProductService class using JUnit. We will use @Test to mark the test methods and assertions to verify the results.

Create a test class ProductServiceTest under the src/test/java directory.

Explanation:

  • @Test: Marks the method as a test method.
  • First Test Method (**testCalculateDiscountedPrice**):
    • Arrange: Set up the necessary inputs (price and discount).
    • Act: Call the method under test (calculateDiscountedPrice).
    • Assert: Verify that the returned result is correct using assertEquals(). We allow a small margin of error using 0.001 as the delta to account for floating-point precision issues.
  • Second Test Method (**testCalculateDiscountedPrice_throwsException_whenInvalid**):
    • Arrange: Set up the input values.
    • Act and Assert: Check that the method throws an IllegalArgumentException when the price is negative using assertThrows().

4. Run the Unit Test

You can run the unit tests in a variety of ways:

  • Using the Command Line: Run the tests with Maven or Gradle using the following command:
    • Maven: mvn test
    • Gradle: gradle test
  • From Your IDE: Most IDEs, like IntelliJ IDEA or Eclipse, provide built-in support to run JUnit tests. You can right-click the test file or class and choose "Run" to execute the tests.

5. Interpret the Results

After running the tests, check the results to ensure they pass:

  • If the tests pass, you’ll see a success message.
  • If any test fails, the output will show an error with the message or assertion that failed.

In our case, the first test checks that the price after a 10% discount is correct, and the second test ensures that the method throws an exception for invalid inputs.

Conclusion

Creating a simple unit test with JUnit in Spring Boot involves setting up the test dependencies, writing the test methods, and using assertions to validate the expected behavior. Unit tests allow you to ensure that your application’s business logic works correctly and helps in early detection of bugs. By following these steps, you can easily test the methods in your Spring Boot services and other components, improving the reliability and quality of your code.

Similar Questions