SpringBoot项目JUnit测试加载ApplicationContext失败求助
Hey there, looking at your error stack trace, the core issue is crystal clear: Spring can't locate a bean of type com.telefonica.backend.service.UserSecurityService when initializing your test context. Let's break down the fixes step by step.
Root Cause
Your SecurityConfig class is autowiring UserSecurityService, but your test context (configured via TestSystemConfig) only imports SecurityConfig—it doesn't tell Spring to scan for your service-layer beans. So Spring has no idea that UserSecurityService exists in your project.
Solution 1: Add Component Scanning to TestSystemConfig
Update your TestSystemConfig to include @ComponentScan targeting your service packages, so Spring can detect and register UserSecurityService (and other service beans):
@Configuration @Import({SecurityConfig.class}) @ComponentScan(basePackages = {"com.telefonica.backend.service"}) // Add this line public class TestSystemConfig { }
Make sure the base package path matches exactly where your UserSecurityService and DriverService classes are located.
Solution 2: Use @SpringBootTest for Simplified Context Setup
If you're working with a Spring Boot app, using @SpringBootTest is often the easiest way to avoid manual context configuration. It automatically loads your full application context (including component scanning, security config, and all other beans):
@SpringBootTest @RunWith(SpringRunner.class) public class DriverServiceTests { @Autowired protected DriverService driverService; @Test public void testFindAll() throws Exception { System.out.println(driverService.findAll()); } }
With this approach, you can even delete the TestSystemConfig entirely—Spring Boot handles all the context setup heavy lifting for you.
Quick Pre-Check
Before applying the above fixes, double-check that your UserSecurityService class has the @Service annotation (or @Component) so Spring recognizes it as a candidate bean:
@Service // Ensure this annotation is present public class UserSecurityService { // ... your service logic here }
Either of these solutions should resolve the NoSuchBeanDefinitionException and let your test load the application context successfully.
内容的提问来源于stack exchange,提问作者Nunyet Calçada

