How to Test Application Context in Spring Boot
Usually, we won't bother about the Junit test for the application context and bean instantiations, blindly trust about the stability of the spring boot framework. And spring boot generates automatically a test class with a method contextLoads()
void contextLoads() {
}
To check the beans are launching properly or not we can frame springboot application like below
public class PracticeApplication {
public static void main(String[] args) {
ConfigurableApplicationContext ctx=SpringApplication.run(PracticeApplication.class, args);
printBeanNames(ctx);
}
Lets deal with the context object
String[] beanDefinitionNames = ctx.getBeanDefinitionNames();
for(String bean:beanDefinitionNames)
System.out.println("BeanNAme is "+bean);
int beanDefinitionCount = ctx.getBeanDefinitionCount();
System.out.println("beanDefinitionCount"+beanDefinitionCount);
}
By running this program we can see a bunch of beans that load while running the application , will be something like this
public TestBean defaultBeanName()
{
return new TestBean("test");
}
record TestBean(String anyvalue){}
and write equivalent test method to check the actual context loading and instantiation
.withUserConfiguration(PracticeApplication.class);
void TestBeanLaunch()
{
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(PracticeApplication.class);
assertThat(it).hasSingleBean(PracticeApplication.TestBean.class);
assertThat(it.getBean("BeanTest")).isInstanceOf(PracticeApplication.TestBean.class);
});
}
Try this , this will help you to gain confidence while testing the application context.
Comments
Post a Comment