The White Rabbit

I would spend 55 minutes defining the problem and then five minutes solving it. (Albert Einstein)

Published on Tuesday, 22 June 2021

Tags: spring-boot2 junit2 java3

[SOLVED] Failed to load ApplicationContext. NoSuchBeanDefinitionException...

When executing any of the JUnit test cases within the Spring Framework in Eclipse a NoSuchBeanDefinitionException is arising. 'No qualifying bean of type ... available: expected at least 1 bean which qualifies as autowire candidate'. Fixed by replacing test class annotation as follows.


Problem

When executing any of the JUnit test cases within the Spring Framework in Eclipse, I got problems described in the console by a very long message containing a chain of errors in this order:

java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'projectService': Unsatisfied dependency expressed through field 'projectRepository';
...
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.mypackage.repository.ProjectRepository' available: expected at least 1 bean which qualifies as autowire candidate.

Solution

I had to replace the test class annotation @SpringBootTest(classes={ProjectAllocationServiceImpl.class}) with @SpringBootTest. Why? The old code was only loading the specified class, but the test cases needed components defined in other classes. By using @SpringBootTest without specifying classes, all class components are loaded.

After doing it, the problem got solved... but a new problem occurred 😀.