服务测试中如何Mock依赖服务?附代码问题求助
Spring Boot ExamServiceImpl 测试修复方案
待测试业务类示例(补全依赖注入)
先明确你的业务类正确结构(补全缺失的依赖注入注解):
@Service public class ExamServiceImpl implements ExamService { @Autowired private TeacherDAO teacherDAO; @Autowired private StudentDAO studentDAO; @Autowired private SubjectService subjectService; // 示例业务方法:获取考试学生列表 public List<Student> getExamStudentList() { return studentDAO.findStudentList(); } // 示例业务方法:获取考试对应科目 public Subject getExamRelatedSubject(Long examId) { return subjectService.getSubjectByExamId(examId); } }
正确的测试类实现
import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.when; @SpringBootTest public class ExamServiceImplTest { // 注入要测试的目标服务 @Autowired private ExamServiceImpl examServiceImpl; // 用@MockBean声明需要Mock的依赖,替换Spring容器中的真实实例 @MockBean private StudentDAO studentDAO; @MockBean private SubjectService subjectService; // 若测试涉及teacherDAO,同样用@MockBean声明 @Test void testGetExamStudentList() { // 构造Mock返回数据 List<Student> mockStudentList = Arrays.asList( new Student(1L, "张三"), new Student(2L, "李四") ); // 配置Mock方法的返回逻辑 when(studentDAO.findStudentList()).thenReturn(mockStudentList); // 调用业务方法 List<Student> result = examServiceImpl.getExamStudentList(); // 断言验证结果 assertNotNull(result); assertEquals(2, result.size()); assertEquals("张三", result.get(0).getName()); } @Test void testGetExamRelatedSubject() { // 构造Mock返回数据 Subject mockSubject = new Subject(101L, "高等数学"); // 配置Mock方法的返回逻辑 when(subjectService.getSubjectByExamId(1L)).thenReturn(mockSubject); // 调用业务方法 Subject result = examServiceImpl.getExamRelatedSubject(1L); // 断言验证结果 assertNotNull(result); assertEquals("高等数学", result.getSubjectName()); } }
核心问题修复说明
- Mock不生效解决:
- 必须用
@MockBean声明需要Mock的依赖(如studentDAO、subjectService),它会替换Spring容器中的真实实例,确保测试时调用的是Mock对象。 - 目标测试服务(examServiceImpl)用
@Autowired注入,它会自动关联被@MockBean替换后的依赖实例。
- 必须用
- 拼写/变量名错误检查:
- 确保测试类中所有变量名、方法名与业务类完全一致,比如
studentDAO不能写成studentDao(大小写错误),subjectService不能拼写成subjetService。
- 确保测试类中所有变量名、方法名与业务类完全一致,比如
- 依赖注入规范:
- 业务类中的依赖必须添加
@Autowired或使用构造器注入,否则Spring无法完成依赖注入,测试时也无法替换为Mock实例。
- 业务类中的依赖必须添加
内容的提问来源于stack exchange,提问作者Jupiter
相关产品推荐
相关产品推荐

