Mockito - Mock没有被注入其中一个测试用例

Eva*_*iam 4 java junit spring unit-testing mockito

我有一个jsf spring应用程序并使用mockito进行单元测试.NullPointerException当我junitiEmployeeService模拟中运行我的测试时,我不断得到.有没有Exception进行iSecurityLoginService.

被嘲笑的方法

@Autowired
IEmployeeService iEmployeeService;
@Autowired
ISecurityLoginService iSecurityLoginService;
public void addEvent() {

    entityEventsCreate.setTitle(entityEventsCreate.getTitle());
    entityEventsCreate.setModifiedBy(iSecurityLoginService
                .findLoggedInUserId());

    int eventId = iEmployeeService.addEmployeeTimeOff(entityEventsCreate);
}
Run Code Online (Sandbox Code Playgroud)

我的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();
}
Run Code Online (Sandbox Code Playgroud)

Bri*_*ice 7

与问题无关,但知道有用!

如果测试用注释@RunWith(MockitoJUnitRunner.class)然后MockitoAnnotations.initMocks(this);没有必要(它甚至可能在注入时引起问题),mockito跑步者执行注射和其他东西来验证模拟.

同时具有两个模拟初始化机制可能会导致注入和存根问题,这是由于JUnit测试的生命周期以及如何使用mockito单元集成代码的方式:

  1. 跑步者将创建模拟并在测试对象中注入这些模拟.
  2. 然后@Before方法启动并重新创建新的模拟,并且可能不会执行注入,因为对象已经初始化.


Eva*_*iam 5

我解决了这个问题.在我的spring bean中,我有2个对象用于相同的服务接口.所以模拟被设置为第一个接口对象.

例如:在我的豆里,

@Autowired
IEmployeeService employeeService;
@Autowired
IEmployeeService iEmployeeService;
Run Code Online (Sandbox Code Playgroud)

因此,为IEmployeeservice接口创建的mock是为第一个与其名称无关的服务对象注入的.

@Mock
IEmployeeService iEmployeeService;
Run Code Online (Sandbox Code Playgroud)

即,模拟对象'iEmployeeService'被注入bean的employeeService'.

感谢所有帮助过的人.. :)