作者:mobiledu2502861417 | 来源:互联网 | 2023-05-19 12:28
我有一个jsf spring应用程序并使用mockito进行单元测试.NullPointerException
当我junit
在iEmployeeService
模拟中运行我的测试时,我不断得到.有没有Exception
进行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();
}
Brice..
7
与问题无关,但知道有用!
如果测试用注释@RunWith(MockitoJUnitRunner.class)
然后MockitoAnnotations.initMocks(this);
没有必要(它甚至可能在注入时引起问题),mockito跑步者执行注射和其他东西来验证模拟.
同时具有两个模拟初始化机制可能会导致注入和存根问题,这是由于JUnit测试的生命周期以及如何使用mockito单元集成代码的方式:
跑步者将创建模拟并在测试对象中注入这些模拟.
然后@Before
方法启动并重新创建新的模拟,并且可能不会执行注入,因为对象已经初始化.
Eva Mariam..
5
我解决了这个问题.在我的spring bean中,我有2个对象用于相同的服务接口.所以模拟被设置为第一个接口对象.
例如:在我的豆里,
@Autowired
IEmployeeService employeeService;
@Autowired
IEmployeeService iEmployeeService;
因此,为IEmployeeservice接口创建的mock是为第一个与其名称无关的服务对象注入的.
@Mock
IEmployeeService iEmployeeService;
即,模拟对象'iEmployeeService'被注入bean的employeeService'.
感谢所有帮助过的人.. :)
1> Brice..:
与问题无关,但知道有用!
如果测试用注释@RunWith(MockitoJUnitRunner.class)
然后MockitoAnnotations.initMocks(this);
没有必要(它甚至可能在注入时引起问题),mockito跑步者执行注射和其他东西来验证模拟.
同时具有两个模拟初始化机制可能会导致注入和存根问题,这是由于JUnit测试的生命周期以及如何使用mockito单元集成代码的方式:
跑步者将创建模拟并在测试对象中注入这些模拟.
然后@Before
方法启动并重新创建新的模拟,并且可能不会执行注入,因为对象已经初始化.
2> Eva Mariam..:
我解决了这个问题.在我的spring bean中,我有2个对象用于相同的服务接口.所以模拟被设置为第一个接口对象.
例如:在我的豆里,
@Autowired
IEmployeeService employeeService;
@Autowired
IEmployeeService iEmployeeService;
因此,为IEmployeeservice接口创建的mock是为第一个与其名称无关的服务对象注入的.
@Mock
IEmployeeService iEmployeeService;
即,模拟对象'iEmployeeService'被注入bean的employeeService'.
感谢所有帮助过的人.. :)