Julian
Julian

Reputation: 4085

How to test Spring boot JdbcTest slice

I am sure I am not the first one to face this but neither spring documentation nor google, nor other posts on this site took me to somewhere I could follow an end to end example so I could adapt it to my use case.

We have a quite complex spring boot application with lots of beans, REST API, messaging and DB integration, scheduled services, etc.

Part of this setup we have a repository bean (say MyRepository) that we want to run some integration tests against to make sure it behaves the way we expect. This is important as it is running some rather complex SQLs which are crucial to stay correct.

The datasource is configured in an application.yaml and all we would like to have is to be able to autowire a JdbcTemplate bean that would allow us to prepare our test data and the instance on MyRepository bean under test. There is important not to load the full application just to make these available.

So far I tried all kind of combinations of @JdbcTest, @ContextConfiguration, @SpringBootTest, @TestConfiguration, etc, etc, I just could not get it to do what I wanted.

On one of my other very old spring projects I created a custom implementation of the org.springframework.test.context.ContextLoader but going like that now that we have spring boot seems to me reinventing the wheel.

We are using spring boot 2.4.6 release.

I would appreciate a few lines of not even running code that would put me on the right track.

Thanks in advance.

Upvotes: 1

Views: 2418

Answers (1)

Julian
Julian

Reputation: 4085

The issue was that we annotated our main class with a custom annotation rather than @SpringBootApplication and such the @JdbcTest was unable to load configuration. I was not aware about this and such scratched my head for a couple of days :-).

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Import({MyCompanyAutoconfiguration.class})
@Inherited
@Documented
@SpringBootApplication
@EnableCircuitBreaker
public @interface MyCompanyApplication {
    @AliasFor(
        annotation = SpringBootApplication.class
    )
    Class<?>[] exclude() default {};

    @AliasFor(
        annotation = SpringBootApplication.class
    )
    String[] excludeName() default {};

    @AliasFor(
        annotation = SpringBootApplication.class
    )
    String[] scanBasePackages() default {};
    
    @AliasFor(
        annotation = SpringBootApplication.class
    )
    Class<?>[] scanBasePackageClasses() default {};
}

Once I added the below code everything started working.

@JdbcTest
@ActiveProfiles("test")
@Import({MyRepository.class})
@ContextConfiguration(classes = MyCompanyApplication.class)
@AutoConfigureTestDatabase(replace= AutoConfigureTestDatabase.Replace.NONE)
public class MyRepositoryTest {
    ...
}

Upvotes: 3

Related Questions