Issue
I have a jsf spring application and using mockito for my unit test. I keep getting NullPointerException
when i run my junit
test in iEmployeeService
mocking. There are not Exception
for iSecurityLoginService
.
Method to be mocked
@Autowired
IEmployeeService iEmployeeService;
@Autowired
ISecurityLoginService iSecurityLoginService;
public void addEvent() {
entityEventsCreate.setTitle(entityEventsCreate.getTitle());
entityEventsCreate.setModifiedBy(iSecurityLoginService
.findLoggedInUserId());
int eventId = iEmployeeService.addEmployeeTimeOff(entityEventsCreate);
}
My JUnit test is annotated with @RunWith(MockitoJUnitRunner.class)
@Mock
ISecurityLoginService iSecurityLoginService;
@Mock
IEmployeeService iEmployeeService;
@InjectMocks
ServiceCalendarViewBean serviceCalendarViewBean = new ServiceCalendarViewBean();
@Before public void initMocks() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testSaveEvent() {
Mockito.when(iSecurityLoginService.findLoggedInUserId()).thenReturn(1);
serviceCalendarViewBean.getEntityEventsCreate().setTitle("Junit Event Testing");
Mockito.when(iSecurityLoginService.findLoggedInUserId()).thenReturn(1);
Mockito.when(iEmployeeService.addEmployeeTimeOff(Mockito.any(Events.class))).thenReturn(2);
serviceCalendarViewBean.addEvent();
}
Solution
I solved the problem..In my spring bean, i had 2 objects for the same service interface. so the mock was being set for the first interface object.
Ex: in my bean i had,
@Autowired
IEmployeeService employeeService;
@Autowired
IEmployeeService iEmployeeService;
So the mock create for the IEmployeeservice interfaces was being inject for the first service object irrelevant for their names.
@Mock
IEmployeeService iEmployeeService;
ie, the mock object 'iEmployeeService' was injected to beans 'employeeService' .
Thank you for all those who helped..:)
Answered By - Eva
Answer Checked By - Clifford M. (JavaFixing Volunteer)