Testing data repositories with Testcontainers
The first step when it comes to using Testcontainers is configuring the test case. To talk to a Postgres database, do this:
@Testcontainers @DataJpaTest @AutoConfigureTestDatabase(replace = Replace.NONE) public class VideoRepositoryTestcontainersTest { @Autowired VideoRepository repository; @Container // static final PostgreSQLContainer<?> database = // new PostgreSQLContainer<>("postgres:9.6.12") // .withUsername("postgres"); }
This framework for test cases can be described as follows:
@Testcontainers
: The annotation from the Testcontainersjunit-jupiter
module that hooks into the life cycle of a JUnit 5 test case.@DataJpaTest
: Spring Boot Test’s annotation we used in the previous section, indicating that all entity classes and Spring Data JPA repositories should be scanned.@AutoConfigureTestDatabase...