有一个如下的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也能够使用了。也不会抛异常了。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
您遇到的问题是在进行单元测试时,Spring的依赖注入没有生效,导致studentInstitutionMapper
为null。这是因为当您直接用new StudentService()
创建对象时,Spring的@Autowired注解不会自动工作,因此依赖的bean(在这里是StudentInstitutionMapper
)没有被注入。
解决方法如您所示,使用JUnit和Mockito框架的特性来正确地模拟(mock)依赖项。这里有几个关键点:
@ExtendWith(MockitoExtension.class):这个注解告诉JUnit使用Mockito扩展来进行测试。它替代了旧版JUnit中的@RunWith(MockitoJUnitRunner.class)。
@Mock:此注解用于创建mock对象。在这个例子中,您使用它来创建一个mock的StudentInstitutionMapper
实例。
@InjectMocks:这个注解用于创建一个实例,其余的mock对象将被自动注入到用该注解标记的类的字段中。在这个场景下,StudentService
类的studentInstitutionMapper
字段将会被自动注入我们之前定义的mock对象。
通过这样的设置,当您在测试方法中调用studentService.getPresentStudentCount(studentParam)
时,studentInstitutionMapper
不再是null,而是由Mockito管理的mock对象。这样就可以顺利执行测试,同时还能控制mock对象的行为,比如预设方法的返回值等,以满足测试的需要。
您的解决方案是正确的,遵循了单元测试中隔离被测组件、控制外部依赖的原则,确保了测试的准确性和可重复性。