我正在尝试在服务层中存根一种方法来测试另一个对象:
@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);
}
}
和调用已测试方法的方法
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;
}
但是当我在hasEmployeeAccessToWorkReport
实例上调用经过测试的方法WorkreportCrudFacade
时,该方法未正确进行存根(应该返回true
,但返回false
)。
我敢肯定这会是一些细节,但我无法找出问题所在-可能是参数匹配器中有问题,但不确定。
我正在使用Mockito 2.22.0。
答案 0 :(得分:0)
由于Mockito any(Class)和anyInt系列匹配器执行类型检查,因此它们将不匹配null参数。而是使用isNull匹配器。
我认为这里会发生以下情况:您的DomainObjectTools
是一个空的模拟(未存根),因此它返回null Workreport
和null Employee
。结果导致调用accessRightsService.hasEmployeeRightsToWorkReport(null,null)
。 null
的值与ArgumentMatchers.any(Class)
不匹配。