Search code examples
javaunit-testingmockitojunit4

Autowired fields of mocked object returns null in Mockito


I have a StudentService class. And I have written a class for unit testing methods of StudentService class. My code is as follows:-

@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();
}


}

And in my unit testing class, I have written following method.

    @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);

    }

when I execute the test class, i get error. This is because in StudentService class, in getPresentStudentCount() method, at line 8, the studentInstitutionMapper field is null. This is happening only for mocked object. How do i get autowired fields of mocked object?


Solution

  • You need to use the @InjectMocks annotation in your unit test :

    @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);
    
        }
    }
    

    You should also configure the behavior of the studentInstitutionMapper in the unit test to make it return the expected result.