Integration Testing examples for Spring Test Slices.
Some links about Test Slices:
@DataJdbcTest applies only the Spring configuration relevant to Data JDBC tests.
Tests run with no DB connection by default:
It can also be configured to use embedded database (H2, DERBY, HSQLDB). With some effort it is also a possible to use embedded PostgreSQL:
By default, tests annotated with @DataJdbcTest are transactional and roll back at the end of each test.
@DataJpaTest provides Spring configuration to support JPA repositories and Entities:
they can also inject TestEntityManager to help testing repositories while using first-level cache.
Additional info for using Kotlin with Spring JPA:
kotlin("plugin.jpa")
provides no-args constructor for our entities (https://stackoverflow.com/a/41365380).
By default, tests annotated with @DataJpaTest are transactional and roll back at the end of each test.
We can use testcontainers to create all of our application beans for integration tests.
- Slowest, but use real database.
- Requires some setup and config values for DB connection:
- Database changes made by tests are not rolled back at the end.
Examples:
EmployeeJdbcRepositoryTestcontainersSpec
EmployeeExposedRepositoryTestcontainersSpec
EmployeeJpaRepositoryTestcontainersSpec
@WebMvcTest annotation can be used to test controllers separately:
- With
MockMvc
- compare also Guide to Testing Spring Boot Applications With MockMvc - With
WebTestClient
- see Spring framework docs for WebTestClient
Usually we use it with @MockBean
for services used by the tested controller.
Examples are provided in:
We can use MockMvc
without @WebMvcTest
annotation
(compare with Setup Choices documentation page).
However, even in standalone mode the servlet context still needs to be created.
This project uses WireMock to record expected answers from 3rd party service. In CatFactClientSpec we:
- specify how WireMock server should respond
- verify that our code can correctly interact with specified response
Spring Cloud Contract describes behaviour of our API with Contract DSL.
- On the producer side:
- Verifies if the server behaves as described in contract
- On the consumer side:
- Creates WireMock stub server to test client code
We can write the contract first, and then implement server and client independently. See also:
Swagger UI is available at http://localhost:8080/swagger-ui/index.html.
./gradlew wrapper --gradle-version latest