Java Testing Cookbook
Snippets to quickly setup common Java/Spring testing scenarios.
Note: The examples below assume spring boot version 3.4.5
or above.
Configuring H2 with Spring
Add h2 maven dependency:
<!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
<!-- Optionally, Assuming JPA is being used -->
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
H2 Maven Dependency
Configure test properties:
spring:
config:
activate:
on-profile: test
datasource:
username: sa
password:
url: jdbc:h2:mem:testdb;MODE=PostgreSQL;DB_CLOSE_DELAY=-1
driver-class-name: org.h2.Driver
application.yaml
Sample test:
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.ActiveProfiles;
import javax.sql.DataSource;
import java.sql.SQLException;
import static org.assertj.core.api.Assertions.assertThat;
@DataJpaTest
@ActiveProfiles("test")
public class SamplePersistenceTest {
@Autowired
private DataSource dataSource;
@DisplayName("Should connect to in memory test database When test context is loaded")
@Test
void shouldConnectToInMemoryTestDatabaseWhenTestContextIsLoaded() throws SQLException {
assertThat(dataSource).isNotNull();
try (final var conn = dataSource.getConnection()) {
final var metadata = conn.getMetaData();
assertThat(metadata)
.isNotNull();
assertThat(metadata.getDriverName())
.isEqualTo("H2 JDBC Driver");
}
}
}
Sample Spring Data Test
Setting Up Spring Controller (Spring Web MVC) Tests
Consider the following sample controller with a /example
route supporting HTTP GET
and POST
methods:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/example")
public class ExampleController {
private final ExampleService service;
@Autowired
public ExampleController(final ExampleService exampleService) {
this.service = exampleService;
}
@GetMapping
public ResponseEntity<ExampleDTO> getExample() {
return service.findRandom()
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@PostMapping
public ResponseEntity<ExampleDTO> createExample(@RequestBody ExampleDTO requestBody) {
try {
final var dto = service.create(requestBody);
return ResponseEntity.status(HttpStatus.CREATED).body(dto);
} catch (final RuntimeException e) {
return ResponseEntity.status(HttpStatus.CONFLICT).build();
}
}
}
Sample Spring Rest Controller
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class ExampleService {
public Optional<ExampleDTO> findRandom() {
return Optional.of(new ExampleDTO(
RandomStringUtils.secure().nextAlphanumeric(10),
RandomUtils.secure().randomInt(),
true
));
}
ExampleDTO create(final ExampleDTO dto) {
return dto;
}
}
Sample Example Service
Sample Spring Web MVC test for the class above is given below:
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;
import java.util.Optional;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(controllers = ExampleController.class)
class ExampleControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@MockitoBean
private ExampleService exampleService;
@DisplayName("Should return http 201 created When posting an example payload")
@Test
void shouldReturnHttp201CreatedWhenPostingAnExamplePayload() throws Exception {
final var dto = new ExampleDTO("Test", 25, true);
when(exampleService.create(dto)).thenReturn(dto);
mockMvc.perform(post("/example")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(dto)))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.name").value("Test"))
.andExpect(jsonPath("$.age").value(25))
.andExpect(jsonPath("$.isActive").value(true));
}
@DisplayName("Should return http 409 conflict When posting an example payload that already exists")
@Test
void shouldReturnHttp409ConflictWhenPostingAnExamplePayloadThatAlreadyExists() throws Exception {
final var dto = new ExampleDTO("Test", 25, true);
when(exampleService.create(dto)).thenThrow(RuntimeException.class);
mockMvc.perform(post("/example")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(dto)))
.andExpect(status().isConflict());
}
@DisplayName("Should return http 200 ok When retrieving a random example is successful")
@Test
void shouldReturnHttp200OkWhenRetrievingARandomExampleIsSuccessful() throws Exception {
final var dto = new ExampleDTO("Test", 25, true);
when(exampleService.findRandom()).thenReturn(Optional.of(dto));
mockMvc.perform(get("/example"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Test"))
.andExpect(jsonPath("$.age").value(25))
.andExpect(jsonPath("$.isActive").value(true));
}
@DisplayName("Should return http 404 not found When no random example is found")
@Test
void shouldReturnHttp404NotFoundWhenNoRandomExampleIsFound() throws Exception {
when(exampleService.findRandom()).thenReturn(Optional.empty());
mockMvc.perform(get("/example")).andExpect(status().isNotFound());
}
}
Sample Spring Web MVC Test