Spring Boot Web Application Integrating Testing with JUnit, AssertJ and Mockito (BDDMockito)
This post briefly captures the process of writing integration tests for a Spring Boot based Web application using JUnit, AssertJ and Mockito (BDDMockito) framework.
Introduction
Unit testing is a type of software testing where individual units or components (ex: a method, a class) of a software are tested .
Integration testing is the phase in software testing in which individual software modules are combined and tested as a group. Integration Test covers multiple units because it tests the interaction between two or more components.
JUnit is a unit testing framework for the Java programming language.
AssertJ is a Java library that provides a rich set of assertions and truly helpful error messages, improves test code readability.
Mockito is a testing framework that allows the creation of test double objects in automated unit tests for the purpose of test-driven development or behavior-driven development.
Goals
- Data/Repository Layer Testing
- Business/Service Layer Testing
- Web/Controller Layer Testing
Test Methodology
given-when-then human readable test methodology is followed here. It lends more clarity to our tests as we are following a natural language that is easy to read.
-
given
pre-conditions and requirements for actions. -
when
action we want to test. -
then
verification of what should happen after execution of action.
Minimum Software Requirements
Note: Ensure JUnit5 is on the project build path.
Sample Project
Spring Boot Minimal Web App is the sample Spring Boot web application i've used to illustrate Integration Testing.
Navigate to http://localhost:8080/ to discover the application URLs.
In the application.properties file present in the resources folder, set the spring.profiles.active value to application-h2db.
Noticed an issue with this Sample Project? Open an issue or a PR on GitHub!
Dependencies
This implementation has a dependency on spring-boot-starter-test, h2, lombok dependencies. The maven/gradle dependencies of the same are mentioned below.
Repository Layer Testing
Repositories are classes or components that encapsulate the logic required to access data sources. They centralize common data access functionality, providing better maintainability and decoupling the infrastructure or technology used to access databases from the domain model layer
Service Layer Testing
Service layer is an architectural pattern, which aims to organize the services, within a service inventory, into a set of logical layers. Services that are categorized into a particular layer share functionality.
Controller Layer Testing
The Controller layer is the conductor of operations for a request. It controls the transaction scope and manages the session related information for the request. The controller first dispatches to a command and then calls the appropriate view processing logic to render the response.