Posts

Showing posts with the label @DataJpaTest

@Sql - Spring Testing Annotation

Image
In this tutorial, we will learn about the @Sql annotation, and at the end, we will see how the Spring Boot application can utilize the @Sql annotation for testing. Therefore, read the post till the end. About @Sql The @Sql is a part of the org.springframework.test.context.jdbc  package. It can be applied at the test class level or the test method level.  Within the Spring testing context, SQL scripts and statements are executed against a database using the Spring @Sql annotation. @Sql declarations at the method level take precedence over those at the class level. But we can change this behavior by configuring @SqlMergeMode .  The annotation supports the following attributes: scripts statements executionPhase config value 1. scripts It specifies the path on which SQL scripts should run. The following example shows how to use it: @Sql (scripts = { "/create-schema.sql" }) public class StudentRepositoryTests { We can specify the path of multiple SQL scripts, like below. @Sql

Spring Boot - Testing a JPA application with @DataJpaTest and Testcontainers

Image
In this section, we will learn how to test Repository layer components with @DataJpaTest and Testcontainers in JPA Spring Boot application that uses PostgreSQL as database . 1.  What we will build? We will create a basic JPA Spring Boot application that uses PostgreSQL as database. We will create Repository layer for this application. Finally we will do a testing with help of Testcontainers to verify our system is working as expected. 2. Testcontainers Testcontainers is an open source testing library that allows us to run docker containers directly in our spring boot application in order to facilitate integration tests with real dependencies.  It can provide instances of common databases(here PostgreSQL),  message brokers, Selenium web browsers, or anything else that can run in a Docker container. 3.  @ DataJpaTest Instead of bootstrapping the entire application context for every test,  @DataJpaTest  allows us to initialize only the parts of the Application context that are relevant to