Having issues with testing Java library with just a configuration?

I’m helping to write a Java library (JAR file) which result is just one @Configuration file that integrates Redis. But the problem became – how to test it?

It turned out, that it’s not so easy to figure out which dependencies to use and HOW to test it. It looks like that jUnit5 / Spring Boot tests really want to have an application to run, even in the tests folder. Otherwise lots of errors appear – tests can not find property placeholders, can not scan classpath and create dependencies etc.

So, how did I solve the problem? A couple of steps:

// Create a "fake" application that lives in src/main/test/java
@SpringBootApplication
public class TestFakeCacheApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestFakeCacheApplication.class, args);
    }

}

// Add tests, that use Redis autoconfiguration all beans
@SpringBootTest
@ExtendWith(SpringExtension.class)
@EnableCaching
@ImportAutoConfiguration(classes = {
    CacheAutoConfiguration.class,
    RedisAutoConfiguration.class
})
@ContextConfiguration(classes = { TestFakeCacheApplication.class })
class CacheApplicationTests {
    @Autowired
    private SomeService whichNotAutowirePreviously;
//...

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *