获取NullPointerException。不知道我在做什么错。任何帮助将不胜感激。
调用时获取NullPointer
Teacher t = teacherService.getTeacherDetails();
我确实进行了调试,并且看到TeacherService为空。我不是为什么它为null,因为我已经在测试类中模拟了此对象。
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;
}
答案 0 :(得分:1)
问题是此代码
@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
完全不再需要