You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring应用正常运行,执行gradle test时出现依赖注入异常求助

解决Spring单元测试中的UnsatisfiedDependencyException问题

我来帮你分析下这个问题——你遇到的UnsatisfiedDependencyException大概率是因为@WebMvcTest和@ContextConfiguration的搭配使用出了问题,咱们一步步来拆解和解决:

问题根源

@WebMvcTest是Spring提供的切片测试注解,专门用于测试Controller层,它会自动加载Spring MVC相关的上下文(包括自动配置MockMvc),并且默认只扫描指定的Controller类。而你额外添加的@ContextConfiguration手动指定了一堆服务类(TokenHandler、LoginService等),这会导致两个核心问题:

  1. 这些服务类本身可能还有自己的依赖(比如数据库DAO、其他组件),但切片测试并没有加载这些依赖,Spring无法创建它们的完整实例
  2. @WebMvcTest已经在处理上下文配置,手动指定类会打乱Spring的自动配置逻辑,导致依赖注入链断裂

正确的解决方案

你只需要做两个关键调整就能解决问题:

1. 移除@ContextConfiguration注解

完全不需要手动指定这些服务类,@WebMvcTest会负责MVC层的上下文配置,我们只需要模拟Controller的依赖即可。

2. 使用@MockBean模拟依赖服务

对于AuthenticationController依赖的TokenHandler、LoginService、UserService,用@MockBean注解来创建它们的Mock实例,Spring会自动把这些Mock注入到Controller中,彻底避免真实依赖的加载问题。

修正后的测试类代码如下:

@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(AuthenticationController.class)
public class AuthenticationControllerTest {

    @Autowired
    private MockMvc mockMvc;

    // 模拟Controller依赖的所有服务类
    @MockBean
    private TokenHandler tokenHandler;

    @MockBean
    private LoginService loginService;

    @MockBean
    private UserService userService;

    // 示例测试方法
    @Test
    public void testLoginSuccess() throws Exception {
        // 先配置Mock的预期行为
        when(loginService.authenticate(anyString(), anyString()))
                .thenReturn(new UserDto("testUser", "test@example.com"));

        // 执行请求并断言结果
        mockMvc.perform(post("/auth/login")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content("{\"username\":\"test\",\"password\":\"123456\"}"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.username").value("testUser"));
    }
}

额外提示

  • @MockBean是Spring Boot提供的注解,它会自动将Mock对象注册到Spring应用上下文中,替代原本的真实Bean,是切片测试场景的最佳实践
  • 如果你的Controller依赖特定配置类,可以用@Import注解引入(比如@Import(AuthConfig.class)),而非@ContextConfiguration
  • 执行gradle test前,可以先运行gradle clean清理旧的测试缓存,避免残留的上下文影响测试结果

内容的提问来源于stack exchange,提问作者David Nagl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:21:56