DEV Community

Cover image for JUnit Testing | Spring Boot | Java Spring
Debesh P.
Debesh P.

Posted on

JUnit Testing | Spring Boot | Java Spring

Testing is a crucial part of software development, ensuring that our applications function as expected. In Spring Boot, we commonly use JUnit for unit testing. If you're new to testing in Spring Boot, this guide will help you get started with JUnit 5, its core assertions, and the difference between assertTrue() and Assert.isTrue().

Setting Up JUnit in Spring Boot

Spring Boot applications typically include JUnit 5 by default. If you need to add it manually, include the following dependency in your pom.xml (for Maven-based projects):

demo

Once added, you’re ready to write unit tests!

JUnit Assertions

JUnit provides various assertion methods to verify expected outputs. Some of the most used assertions include:

  • assertEquals(expected, actual): Checks if two values are equal.

  • assertNotEquals(expected, actual): Checks if values are not equal.

  • assertTrue(condition): Ensures a condition is true.

  • assertFalse(condition): Ensures a condition is false.

  • assertNotNull(object): Checks if an object is not null.

  • assertNull(object): Ensures an object is null.

Here’s an example:

demo

assertTrue() vs. Assert.isTrue()

Many developers get confused between JUnit’s assertTrue() and Spring’s Assert.isTrue(). Let's clarify their differences.

1. assertTrue() (JUnit Assertion)

This method belongs to JUnit and is used for unit testing. If the condition is false, the test fails.

Example:

demo

2. Assert.isTrue() (Spring Utility)

This method belongs to Spring’s org.springframework.util.Assert class. It is used for runtime validation inside your application, not in unit tests. If the condition is false, it throws an IllegalArgumentException.

Example:

demo

If age were less than 18, this would throw an IllegalArgumentException.

Key Differences

Feature assertTrue() Assert.isTrue()
Package org.junit.jupiter.api.Assertions org.springframework.util.Assert
Purpose Used in unit tests Used for runtime validation
Failure Behavior Fails test with an error message Throws IllegalArgumentException
Usage assertTrue(condition, message) Assert.isTrue(condition, message)

Writing Unit Tests in a Spring Boot Application

Let’s apply what we’ve learned by testing a simple Spring Boot service.

Sample Service Class

demo

Writing a Test for the Service

Image description

Conclusion

Testing with JUnit in Spring Boot helps you write reliable, bug-free code. With the right assertions, test lifecycle management, and integration tests, you can ensure your app runs smoothly. Keep testing, keep improving, and build with confidence!

Top comments (0)