What is equivalent to @DataJpaTest if I just want to check the JdbcTemplate code?

Spring Boot 1.4 offers some fantastic improvements in testing. One of them is the @DataJpaTest annotation, where it connects only those parts that are necessary for testing JPA. What would the equivalent look like just by running the components needed for the JdbcTemplate tests?

I am beautifully constructing my own composite annotation that mimics @DataJpaTest .

+6
source share
1 answer
Good question. Oddly enough, this one was picked up during a test conversation yesterday on the SpringOne platform. Let's see what is needed to implement such a special test annotation.

TL;DR check github code

First of all you need to create an annotation. This annotation reuses some bits from the spring-boot-test-autoconfigure module. You can configure automatic tuning of the database in memory (e.g. DataJpaTest ). You must also ensure that caching is configured and disabled by default (if you have @EnableCaching in your Spring Boot application). You also want all your tests to be @Transactional by default, so you should add this.

Then you want the slicing to hit efficiently. All you need at this point is a DataSource , JdbcTemplate , database migration (flyway / Liquibase), and a transaction manager to handle @Transactional . To avoid other auto configurations, you should add the following:

 @OverrideAutoConfiguration(enabled = false) 

Then you want to explicitly enable autoconfiguration above. To do this, add @ImportAutoConfiguration and add the following content to META-INF/spring.factories

 # AutoConfigureDataJpa auto-configuration imports com.example.test.autoconfigure.jdbc.DataJdbcTest=\ org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\ org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\ org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\ org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\ org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\ org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration 

The key in spring.factories should match the FQN of your annotation. Whenever Spring Boot finds @ImportAutoConfiguration without additional attributes, it will look for a key that matches the type of annotation in spring.factories .

Next, you want to enable additional components (component scanning) with a filter. For this, you can add @TypeExcludeFilters(DataJdbcTypeExcludeFilter.class) , where DataJdbcTypeExcludeFilter is almost the same as DataJpaTypeExcludeFilter (so we may need to extract a common class for it).

After you have done this, you need to add your annotation and JdbcTemplate automatically configured for you

 @RunWith(SpringRunner.class) @DataJdbcTest public class DataJdbcSampleTests { @Autowired private JdbcTemplate jdbcTemplate; ... } 
+14
source

All Articles