有一个如下的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);
}
然后,当我在使用时出现了NullPointerException异常,异常原因是因为studentInstitutionMapper是null。这在我只有使用mock时候才会导致的。
原因分析是因为在使用Mock时候,studentInstitutionMapper不能够被自动装配。解决方法如下:
@ExtendWith(MockitoExtension.class)
class StudentServiceTest {
@Mock
private StudentInstitutionMapper studentInstitutionMapper;
@InjectMocks
private StudentService studentService;
@Test
public void testStudentService_getPresentStudentCount1() {
StudentParams studentParam = mock(StudentParams.class);
Integer institutionTestId = 3539;
when(studentParam.getInstitutionTestId()).thenReturn(institutionTestId);
int i = studentService.getPresentStudentCount(studentParam);
assertEquals(0, i);
}
}
我们需要用@Mock标签去注释studentInstitutionMapper,这样子mock也能够使用了。也不会抛异常了。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。