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()


@Test
void contextLoads() {

}

To check the beans are launching properly or not we can frame springboot application like below 


@SpringBootApplication
public class PracticeApplication {

public static void main(String[] args) {

ConfigurableApplicationContext ctx=SpringApplication.run(PracticeApplication.class, args);
printBeanNames(ctx);

}

Lets deal with the context object 

private static void printBeanNames(ApplicationContext ctx) {
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 



BeanNAme is liveReloadServerEventListener
BeanNAme is org.springframework.boot.devtools.autoconfigure.LocalDevToolsAutoConfiguration
BeanNAme is spring.devtools-org.springframework.boot.devtools.autoconfigure.DevToolsProperties
BeanNAme is org.springframework.aop.config.internalAutoProxyCreator
beanDefinitionCount156

Lets test bean loading with custom class, for that create class like below

@Bean("BeanTest")
public TestBean defaultBeanName()
{
return new TestBean("test");
}
record TestBean(String anyvalue){}


and write equivalent test method to check the actual context loading and instantiation

ApplicationContextRunner context = new ApplicationContextRunner()
.withUserConfiguration(PracticeApplication.class);
@Test
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

Popular posts from this blog

SOLID Principle (Quick Read)

Design Patterns

Building a Smart Holiday Booking System with Agent-to-Agent Communication