Домой United States USA — software Spring Boot + Testcontainers + DbRider + P6spy: Testing Relational Databases

Spring Boot + Testcontainers + DbRider + P6spy: Testing Relational Databases

144
0
ПОДЕЛИТЬСЯ

In this article, you will find the approach of writing integration tests for the persistence layer using Spring Boot, Testcontainers, DbRider, Datasource Proxy.
Join the DZone community and get the full member experience. All test examples are persistence layer agnostic — it means that the persistence layer can be implemented only using JDBC specification (without JPA specification). This is the second article about Persistence Layer implementation and testing. The first article can be found here. Also, you can find the full source code on the GitHub page. But now let’s jump right into the tests. First of all, we will create our own annotation @PersistenceLayerTest and hide all configurations there. So our tests will look as follows: The content of the annotation: We will start with @DataJpaTest annotation as it is the main annotation that tells the Spring framework to load the context for the test. It is also one of the ways to ‘slice’ your application (see here more about ‘slice’ annotations). In our case, we ask Spring to load only database-related beans. You can notice that we disable the out-of-the-box feature ‘ showSql.’ We did it because default logging does not show the actual query parameters. Here is an example of the default logging: To solve this problem we can use a data source proxy ( p6spy proxy in our case) that will log queries nicely like this: There is a nice spring-boot-starter for configuring the data source proxy automatically. All we need to do is to bring the dependency: and configure it with a couple of properties: Take note that we disabled proxy by default. Ideally, we would like to choose tests that need to have SQL logging. And it is done by another custom annotation @EnableSqlLogging: Here we declared proxy auto-configuration explicitly as some Spring slices ignore it by default (for instance: DataJpsTest slice). I personally keep SQL logging only for the Persistence Layer test + some rare cases on the other layers. Now, let’s think about where we will get the database for testing. The best practice is to keep the test environment as similar to the production environment as possible. So we will use the same database as in production (MySQL in our case).

Continue reading...