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

Spring + Powermock + JUnit call another service from one service - NullPointerException

获取 NullPointerException。不确定我做错了什么。任何帮助将不胜感激。

调用时获取 NullPointer

Teacher t = teacherService.getTeacherDetails();

我进行了调试,发现 teacherService 为空。我不是为什么它为 null 因为我已经在我的测试中模拟了这个对象 class.

StudentServiceTest.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();

    }

StudentService.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;
    }

TeacherService.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