开发者社区 问答 正文

Autowired fields of mocked object returns null

有一个如下的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也能够使用了。也不会抛异常了。

展开
收起
大俊哥哥 2019-11-23 20:17:07 613 分享 版权
阿里云 AI 助理回答

您遇到的问题是在进行单元测试时,Spring的依赖注入没有生效,导致studentInstitutionMapper为null。这是因为当您直接用new StudentService()创建对象时,Spring的@Autowired注解不会自动工作,因此依赖的bean(在这里是StudentInstitutionMapper)没有被注入。

解决方法如您所示,使用JUnit和Mockito框架的特性来正确地模拟(mock)依赖项。这里有几个关键点:

  1. @ExtendWith(MockitoExtension.class):这个注解告诉JUnit使用Mockito扩展来进行测试。它替代了旧版JUnit中的@RunWith(MockitoJUnitRunner.class)。

  2. @Mock:此注解用于创建mock对象。在这个例子中,您使用它来创建一个mock的StudentInstitutionMapper实例。

  3. @InjectMocks:这个注解用于创建一个实例,其余的mock对象将被自动注入到用该注解标记的类的字段中。在这个场景下,StudentService类的studentInstitutionMapper字段将会被自动注入我们之前定义的mock对象。

通过这样的设置,当您在测试方法中调用studentService.getPresentStudentCount(studentParam)时,studentInstitutionMapper不再是null,而是由Mockito管理的mock对象。这样就可以顺利执行测试,同时还能控制mock对象的行为,比如预设方法的返回值等,以满足测试的需要。

您的解决方案是正确的,遵循了单元测试中隔离被测组件、控制外部依赖的原则,确保了测试的准确性和可重复性。

有帮助
无帮助
AI 助理回答生成答案可能存在不准确,仅供参考
0 条回答
写回答
取消 提交回答
问答标签:
问答地址: