【发布时间】:2018-12-26 18:45:10
【问题描述】:
获取 NullPointerException。不知道我做错了什么。任何帮助将不胜感激。
调用时获取NullPointer
Teacher t = teacherService.getTeacherDetails();
我进行了调试,发现teacherService 为空。我不是为什么它为空,因为我已经在我的测试类中模拟了这个对象。
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;
}
【问题讨论】:
-
既然您是在对
StudentService进行单元测试,那么您应该只将模拟注入到您的StudentService实例中,包括TeacherService的模拟实例 -
getStudentInformaition()返回什么?Student s? -
@StalemateOfTuning 是的,已更新
标签: spring-boot junit mockito powermock