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
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; ... }
source share