Spring + Powermock + JUnit 从一个服务调用另一个服务 - NullPointerExcepti



Get NullPointerException.不知道我做错了什么。任何帮助将不胜感激。

调用时获取空指针

Teacher t = teacherService.getTeacherDetails();

我做了调试,看到老师服务为空。我不是为什么它是空的,因为我已经在测试类中嘲笑这个对象。

学生服务测试.java

@RunWith(PowerMockRunner.class)
@PrepareForTest({StudentService.class, TeacherService.class})
public class StudentServiceTest{
    @InjectMocks
    StudentService studentService;
    @InjectMocks
    TeacherService teacherService;
    @Mock
    private StudentRepository studentRepository;
    @Mock
    private TeacherRepository teacherRepository;
    @Test
    public void getStudentInformation() {
        Student student = new Student();
        Teacher teacher = new Teacher();
        when(studentRepository.getStudentDetails()).thenReturn(student);
        when(teacherRepository.getTeacherDetails()).thenReturn(teacher);
        Student student = studentService.getStudentInformaition();
    }

学生服务.java

   private TeacherService teacherService;
   @Autowired
    public StudentService(TeacherService teacherService) {
        this.teacherService = teacherService;
    }
    public Student getStudentInformaition() {
        Teacher t = teacherService.getTeacherDetails();
        // some logic
        Student s = studentRepository.getStudentDetails();
       // some more logic
       return s;
    }

教师服务.java

 public Teacher getTeacherDetails() {
        Teacher t = teacherRepository.getTeacherDetails();
        return t;
    }

问题是这段代码

@InjectMocks
StudentService studentService;

将定义的模拟对象实例注入studentService实例,但TeacherService的实例不是模拟,因此不会作为模拟注入到studentService实例中。

您应该将代码调整为如下所示的内容:

@RunWith(PowerMockRunner.class)
@PrepareForTest({StudentService.class, TeacherService.class})
public class StudentServiceTest{
    @InjectMocks
    StudentService studentService;
    @Mock
    TeacherService teacherService;
    @Mock
    private StudentRepository studentRepository;
    @Test
    public void getStudentInformation() {
        Student student = new Student();
        Teacher teacher = mock(Teacher.class);
        when(studentRepository.getStudentDetails()).thenReturn(student);
        when(teacherService.getTeacherDetails()).thenReturn(teacher);
        when(teacher.getFoo()).thenReturn(???);
        Student student = studentService.getStudentInformaition();
    }

请注意,teacherService 现在是一个模拟对象实例,不再需要TeacherRepository

相关内容

  • 没有找到相关文章

最新更新