Felpfe Inc.
Search
Close this search box.
call 24/7

+484 237-1364‬

Search
Close this search box.

Unit Testing with JUnit and Mockito

Unit testing is a critical aspect of software development that focuses on testing individual units or components of an application in isolation. It ensures that each component works correctly and produces the expected output. In Spring Boot, unit testing is made easier with the help of popular testing frameworks like JUnit and Mockito. This section will introduce you to unit testing in Spring Boot using JUnit and Mockito, along with code samples to illustrate the concepts.

1. Introduction to Unit Testing
Unit testing involves testing individual units or components of code, such as methods, functions, or classes, in isolation. The goal is to validate the behavior of these units and ensure they function correctly as standalone entities. By isolating the units, unit tests can identify and fix bugs early in the development process, leading to more reliable and maintainable code.

2. Setting Up JUnit and Mockito in a Spring Boot Project
To use JUnit and Mockito for unit testing in a Spring Boot project, you need to include the necessary dependencies in your project’s build configuration. Here’s an example of how to add these dependencies using Maven:

“`xml
<dependencies>
<!– Spring Boot Test Starter for JUnit 5 –>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<!– Mockito Core –>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
“`

3. Writing Unit Tests with JUnit
JUnit is a widely-used testing framework for Java applications. It provides annotations, assertions, and utilities to write and execute unit tests. Let’s look at an example of a unit test for a simple calculator class using JUnit:

“`java
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class Calculator {
int add(int a, int b) {
return a + b;
}
}

class CalculatorTest {

private Calculator calculator;

@BeforeEach
void setUp() {
calculator = new Calculator();
}

@Test
void testAdd() {
int result = calculator.add(2, 3);
assertEquals(5, result);
}
}
“`

In the above example, we have a `Calculator` class with an `add` method that adds two integers. The `CalculatorTest` class is the unit test class for the `Calculator` class. The `setUp` method is annotated with `@BeforeEach` and is executed before each test case to set up the necessary objects. The `testAdd` method is annotated with `@Test` and contains the actual test logic. We use the `assertEquals` method to compare the expected result with the actual result.

4. Mocking Dependencies with Mockito
In real-world applications, classes often depend on other classes or external dependencies. Mockito is a popular mocking framework that allows us to create mock objects and define their behavior during tests. This helps isolate dependencies and focus on testing specific components.

Let’s consider an example where we have a `PaymentService` class that depends on an external payment gateway. We can mock the payment gateway using Mockito and test the `PaymentService` class in isolation:

“`java
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.*;

class PaymentGateway {
boolean processPayment(double amount) {
// Logic to process payment
return true;
}
}

class PaymentService {
private PaymentGateway paymentGateway;

PaymentService(PaymentGateway paymentGateway) {
this.paymentGateway =

paymentGateway;
}

boolean makePayment(double amount) {
// Business logic to make payment
return paymentGateway.processPayment(amount);
}
}

class PaymentServiceTest {

private PaymentGateway paymentGateway;
private PaymentService paymentService;

@BeforeEach
void setUp() {
paymentGateway = mock(PaymentGateway.class);
paymentService = new PaymentService(paymentGateway);
}

@Test
void testMakePayment() {
when(paymentGateway.processPayment(100.0)).thenReturn(true);
boolean result = paymentService.makePayment(100.0);
assertTrue(result);
verify(paymentGateway, times(1)).processPayment(100.0);
}
}
“`

In the above example, we have a `PaymentService` class that depends on a `PaymentGateway` class. The `PaymentService` class uses the `PaymentGateway` to process payments. In the `PaymentServiceTest` class, we create a mock object of the `PaymentGateway` class using `mock(PaymentGateway.class)`. We define the behavior of the mock object using the `when` method. In the `testMakePayment` method, we verify that the `makePayment` method of `PaymentService` returns the expected result when the mocked `PaymentGateway` is called.

5. Conclusion
In this section, we explored the fundamentals of unit testing in Spring Boot using JUnit and Mockito. We discussed the importance of unit testing and how it helps in identifying and fixing bugs early in the development process. We also saw code examples demonstrating how to write unit tests using JUnit and Mockito.

Unit testing is a crucial part of building reliable and maintainable applications, and Spring Boot provides excellent support for unit testing through the integration of JUnit and Mockito. In the next sections, we will delve deeper into integration testing, end-to-end testing, performance testing, and best practices for testing and deploying Spring Boot applications.

About Author
Ozzie Feliciano CTO @ Felpfe Inc.

Ozzie Feliciano is a highly experienced technologist with a remarkable twenty-three years of expertise in the technology industry.

kafka-logo-tall-apache-kafka-fel
Stream Dream: Diving into Kafka Streams
In “Stream Dream: Diving into Kafka Streams,”...
ksql
Talking in Streams: KSQL for the SQL Lovers
“Talking in Streams: KSQL for the SQL Lovers”...
spring_cloud
Stream Symphony: Real-time Wizardry with Spring Cloud Stream Orchestration
Description: The blog post, “Stream Symphony:...
1_GVb-mYlEyq_L35dg7TEN2w
Kafka Chronicles: Saga of Resilient Microservices Communication with Spring Cloud Stream
“Kafka Chronicles: Saga of Resilient Microservices...
kafka-logo-tall-apache-kafka-fel
Tackling Security in Kafka: A Comprehensive Guide on Authentication and Authorization
As the usage of Apache Kafka continues to grow in organizations...
1 2 3 58
90's, 2000's and Today's Hits
Decades of Hits, One Station

Listen to the greatest hits of the 90s, 2000s and Today. Now on TuneIn. Listen while you code.