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

控制器单元测试报UnsatisfiedDependencyException求助

问题原因分析

@WebMvcTest是Spring Boot专门用于专注测试Spring MVC控制器的注解,它只会自动配置与Web层相关的组件(比如控制器、视图解析器、消息转换器等),不会加载持久层(Repository)相关的Bean。你的MultiplicationResultAttemptController构造函数依赖了MultiplicationResultAttemptRepository,但测试类只Mock了MultiplicationService,没有处理Repository的依赖,导致Spring容器找不到对应的Bean实例,从而抛出UnsatisfiedDependencyException。

给Repository加@Repository注解无效的原因是:@WebMvcTest的上下文范围不包含持久层组件的扫描加载,哪怕加了该注解,Spring也不会在这个测试上下文里创建Repository的Bean。

解决方案

方案1:Mock Repository(仅测试Controller的MVC逻辑)

如果你的测试只需要验证Controller的请求映射、参数绑定、返回值处理等MVC层面的逻辑,不需要Repository的真实行为,直接用@MockBean注解Mock这个Repository即可,Spring会将Mock的Bean注入到Controller中:

@WebMvcTest(MultiplicationResultAttemptController.class)
class MultiplicationResultAttemptControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private MultiplicationService multiplicationService;

    // 新增Mock Repository的注解
    @MockBean
    private MultiplicationResultAttemptRepository resultAttemptRepository;

    // 编写测试方法...
}

方案2:加载完整上下文(需要Repository真实行为时)

如果你的测试需要依赖Repository的真实操作(比如验证数据库中是否正确保存了结果),那么@WebMvcTest就不适用了,应该使用@SpringBootTest配合@AutoConfigureMockMvc,这样会加载完整的Spring应用上下文,包括Repository层的Bean:

@SpringBootTest
@AutoConfigureMockMvc
class MultiplicationResultAttemptControllerIntegrationTest {

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private MultiplicationResultAttemptRepository resultAttemptRepository;

    @MockBean
    private MultiplicationService multiplicationService;

    // 编写测试方法...
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 17:40:45