In Spring Boot, if you look at the official documentation, there is a lot of ways to test things and we end up in the AnnotationMania © which is from my point of view, "too magic for me".
In this article, we will explore an alternative solution which is more readable and simpler to implements.
Like Josh Long said, everything starts in start.spring.io. I've just created a simple project without any dependency.
@Configuration Class
Then, I have created this kind of configuration class, which is pretty usual in Spring Boot Projects:
@Configuration
public class ExampleConfiguration {
@Bean
ExampleService exampleService() {
return new ExampleService();
}
}
Test the @Configuration Class
I would like to test this class with a very simple configuration. To do that, I choose to use the tooling usually used by libraries in Spring Boot environment.
So, the test will look like this:
class ExampleConfigurationTest {
/*
* I setup a context runner with the class ExampleConfiguration
* in it. For that, I use ApplicationContextRunner#withUserConfiguration()
* methods to populate the context.
*/
ApplicationContextRunner context = new ApplicationContextRunner()
.withUserConfiguration(ExampleConfiguration.class);
@Test
public void should_check_presence_of_example_service() {
/*
* We start the context and we will be able to trigger
* assertions in a lambda receiving a
* AssertableApplicationContext
*/
context.run(it -> {
/*
* I can use assertThat to assert on the context
* and check if the @Bean configured is present
* (and unique)
*/
assertThat(it).hasSingleBean(ExampleService.class);
});
}
}
With that, you can unit test your @Configuration
classes without any problem.
Thanks to the ApplicationContextRunner you will be able to do a lot thing to test your code, like:
- Add Bean to your context
- Load AutoConfiguration classes
- Set properties
- Modify the ClassLoader to remove some class
And with the AssertableApplicationContext, you will be able to:
- Check the presence of bean
- Get Bean from the context
- Check if the context has failed
Thanks to that, you will be able to unit-test every @Configuration
class simply, without complexity 🚀.
You can check out the whole code here
Top comments (0)