Skip to content

wiiitek/its

Repository files navigation

its

CI sonarcloud.io

Integration Testing examples for Spring Test Slices.

Some links about Test Slices:

@DataJdbcTest

@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

@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.

@Testcontainers

We can use testcontainers to create all of our application beans for integration tests.

  1. Slowest, but use real database.
  2. Requires some setup and config values for DB connection:
  3. Database changes made by tests are not rolled back at the end.

Examples:

@WebMvcTest

@WebMvcTest annotation can be used to test controllers separately:

  1. With MockMvc - compare also Guide to Testing Spring Boot Applications With MockMvc
  2. 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.

WireMock

This project uses WireMock to record expected answers from 3rd party service. In CatFactClientSpec we:

  1. specify how WireMock server should respond
  2. verify that our code can correctly interact with specified response

Spring Cloud Contract

Spring Cloud Contract describes behaviour of our API with Contract DSL.

  1. On the producer side:
    • Verifies if the server behaves as described in contract
  2. 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:

Springfox

Swagger UI is available at http://localhost:8080/swagger-ui/index.html.