【发布时间】:2019-11-15 12:39:45
【问题描述】:
我有一个StudentService 课程。我已经为StudentService 类的单元测试方法编写了一个类。我的代码如下:-
@Component
@EnableAutoConfiguration
public class StudentService {
@Autowired
StudentInstitutionMapper studentInstitutionMapper;
public Integer getPresentStudentCount(StudentParams studentParam) {
// TODO Auto-generated method stub
StudentInstitutionExample example = new StudentInstitutionExample();
StudentInstitutionExample.Criteria criteria = example.createCriteria();
criteria.andActiveYnEqualTo("Y");
criteria.andDeleteYnEqualTo("N");
criteria.andIsPresentEqualTo("Y");
criteria.andInstitutionTestIdEqualTo(studentParam.getInstitutionTestId());
List<StudentInstitution> studentInstitutionList = studentInstitutionMapper.selectByExample(example);//line 8 in method
return studentInstitutionList.size();
}
}
在我的单元测试课中,我编写了以下方法。
@Test
public void testStudentService_getPresentStudentCount1()
{
StudentService service=new StudentService();
StudentParams studentParam=mock(StudentParams.class);
Integer institutionTestId=3539;
when(studentParam.getInstitutionTestId()).thenReturn(institutionTestId);
int i=service.getPresentStudentCount(studentParam);
assertEquals(0,i);
}
当我执行测试类时,我得到了错误。这是因为在StudentService 类中,在getPresentStudentCount() 方法中,在第8 行,studentInstitutionMapper 字段是null。这只发生在模拟对象上。如何获取模拟对象的自动装配字段?
【问题讨论】:
标签: java unit-testing mockito junit4