Testing in Spring Boot
In Spring Boot, testing is made easy and accessible with different types for varying test scopes, such as unit and integration tests.
Remember, the goal of testing is not to prove that functions work, but rather to identify when they don’t, particularly during changes or updates in the codebase. This ensures the reliability and robustness of your application.
Test Structure
project/
|-- src/
| |-- main/
| |-- java/
| |-- com/
| |-- example/
| |-- YourApplication.java
|-- test/
| |-- java/
| |-- com/
| |-- example/
| |-- YourApplicationTests.java
|-- testIntegration/
|-- java/
|-- com/
|-- example/
|-- YourApplicationIT.javaEstablish a clear test structure in your project. Create a test folder for unit tests and a testIntegration folder for integration tests, in line with your application’s package structure.
Unit Tests
Spring Boot works out-of-the-box with JUnit, a popular testing framework in Java. To write a test, you will typically create a new Java class in your test directory. This class will contain methods that each test a specific part of your application code. Annotate these methods with the @Test annotation to signal to JUnit that they are test methods.
Here’s an example test class:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class CalculatorTest {
@Test
public void addsTwoNumbers() {
Calculator calculator = new Calculator();
int result = calculator.add(1, 2);
assertEquals(3, result);
}
}Integration Tests
Spring Boot provides the @SpringBootTest annotation to facilitate integration testing. It can be used in conjunction with @Test and is responsible for loading the full application context during testing.
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void fetchesUserById() {
User user = userService.fetchById(1L);
assertEquals("Alice", user.getName());
}
}