Mockito – Mock没有被注入其中一个测试用例
我有一个jsf spring应用程序并使用mockito进行unit testing。 当我在iEmployeeService
运行junit
测试时,我不断收到NullPointerException
。 iSecurityLoginService
没有Exception
。
要嘲笑的方法
@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)
注释,那么MockitoAnnotations.initMocks(this);
没有必要(它甚至可能在注射时引起问题),mockito跑步者执行注射和额外的东西来validation嘲笑。
同时具有两个模拟初始化机制可能会导致注入和存根问题,这是由于JUnit测试的生命周期以及如何使用mockito单元集成代码的方式:
- 跑步者将创建模拟并在测试对象中注入这些模拟。
- 然后
@Before
方法启动并重新创建新的@Before
,并且可能不会执行注入,因为对象已经初始化。
我解决了这个问题。在我的spring bean中,我有两个对象用于相同的服务接口。 所以模拟被设置为第一个接口对象。
例如:在我的豆里,
@Autowired IEmployeeService employeeService; @Autowired IEmployeeService iEmployeeService;
因此,为IEmployeeservice接口创建的mock是为第一个与其名称无关的服务对象注入的。
@Mock IEmployeeService iEmployeeService;
即,模拟对象’iEmployeeService’被注入bean的employeeService’。
感谢所有帮助过的人.. 🙂
尝试添加此function
@Before public void initMocks() { MockitoAnnotations.initMocks(this); }
我有一个类似的问题,经过一些研究,我发现看起来@InjectMocks
没有工作,并且没有注入@AutoWired
私有对象而无声地失败,
解决方案:通过构造函数使依赖项可见来更改设计,
IEmployeeService iEmployeeService; ISecurityLoginService iSecurityLoginService; @Autowired public ServiceCalendarViewBean(final IEmployeeService iEmployeeService, final ISecurityLoginService iSecurityLoginService){ this.iEmployeeService=iEmployeeService; this.iSecurityLoginService=iSecurityLoginService; }
这个链接帮助我确定了如何处理不可见的@Autowired
对象