Search code examples
springmockitostubbing

Mockito mock is not properly matching arguments (?)


I'm trying to stub one method in service layer for testing another object:

@SpringBootTest
@RunWith(JUnitPlatform.class)
class WorkreportCrudFacadeTest {

  private static Logger LOGGER = LogManager.getLogger(WorkreportCrudFacadeTest.class);

  @Test
  public void detailTest() {

    final AccessRightsService ars = Mockito.mock(AccessRightsService.class);
    final SystemPriceSettingService spss = Mockito.mock(SystemPriceSettingService.class);
    final WorkreportActivityRepository wrar = Mockito.mock(WorkreportActivityRepository.class);
    final WorkreportRepository wrr = Mockito.mock(WorkreportRepository.class);
    final DomainObjectTools dot = Mockito.mock(DomainObjectTools.class);
    final ApplicationEventPublisher aep = Mockito.mock(ApplicationEventPublisher.class);

    Mockito.when(ars.hasEmployeeRightsToWorkReport(
        ArgumentMatchers.any(Employee.class), ArgumentMatchers.any(Workreport.class)
        )
    ).thenReturn(true);

    final WorkreportCrudFacade s = new WorkreportCrudFacade(ars, spss, wrar, wrr, dot, aep);

    final EmployeeId employeeId = new EmployeeId(154149756298300L);
    final WorkreportId workreportId = new WorkreportId(154149757395700L);

    final Workreport detail = s.detail(workreportId, employeeId);

    LOGGER.debug("Detail: {}", detail);

  }

}

and method that invokes tested method:

  public Workreport detail(final WorkreportId workreportId, final EmployeeId employeeId) {

    final Workreport workreport = domainObjectTools.getWorkreportOrThrowNotFoundException(workreportId);
    final Employee viewer = domainObjectTools.getEmployeeOrThrowNotFoundException(employeeId);

    boolean hasRights = accessRightsService.hasEmployeeRightsToWorkReport(viewer, workreport);

    LOGGER.debug("Has rights: {}", hasRights);

    if (!hasRights) {
      throw new ForbiddenException();
    }

    return workreport;

  }

but when I call tested method hasEmployeeAccessToWorkReport on WorkreportCrudFacade instance, the method is not properly stubbed (it should return true, but returns false).

I'm sure it'll be some detail but I'm not able to find out what is wrong - probably something in argument matcher, but not sure.

I'm using Mockito 2.22.0.


Solution

  • Citing from ArgumentMatchers javadoc:

    Since Mockito any(Class) and anyInt family matchers perform a type check, thus they won't match null arguments. Instead use the isNull matcher.

    I think that the following happens here: Your DomainObjectTools is an empty mock (not stubbed) and thus it returns null Workreport and null Employee. It results in calling accessRightsService.hasEmployeeRightsToWorkReport(null,null). The null values are not matched by ArgumentMatchers.any(Class).