我有一个 jsf spring 应用程序并使用mockito对于我的单元测试。我不断得到NullPointerException
当我运行我的junit
测试在iEmployeeService
嘲笑。没有Exception
for iSecurityLoginService
.
被嘲笑的方法
@Autowired
IEmployeeService iEmployeeService;
@Autowired
ISecurityLoginService iSecurityLoginService;
public void addEvent() {
entityEventsCreate.setTitle(entityEventsCreate.getTitle());
entityEventsCreate.setModifiedBy(iSecurityLoginService
.findLoggedInUserId());
int eventId = iEmployeeService.addEmployeeTimeOff(entityEventsCreate);
}
我的 JUnit 测试注释为@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();
}
与问题无关,但了解很有用!
如果测试注释为@RunWith(MockitoJUnitRunner.class)
then MockitoAnnotations.initMocks(this);
没有必要(它甚至可能在注入时导致问题),mockito 运行程序会执行注入和其他内容来验证模拟。
此外,同时拥有模拟初始化机制可能会导致注入和存根问题,这是由于 JUnit 测试的生命周期以及如何使用 mockito 单元集成代码造成的:
- 运行程序将创建模拟并将这些模拟注入测试对象中。
- 然后
@Before
方法启动并重新创建新的模拟,并且可能不会执行注入,因为对象已经初始化。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)