【发布时间】:2019-10-24 17:31:18
【问题描述】:
方法“ContractService”的返回是方法“checkPgwContract”的返回值。我已经模拟了 ContractService 类和 ContractServiceManager 类,但是 checkPgwContract 的方法总是在我的单元测试中通过。
ContractServiceImpl
@Override
public List getListOfContractBy(String contractNo) {
List<OasysContract> oasysContractList = oasysContractRepository.findByContractNumber(contractNo);
if (!oasysContractList.isEmpty()) {
return oasysContractList;
} else {
List<Contract> pgwContractList = contractRepository.findContractsByContractNumber(contractNo);
if (!pgwContractList.isEmpty()) {
return contractServiceManager.checkPgwContract(pgwContractList);
}
}
return new ArrayList();
}
ContractServiceManagerImpl
private boolean checkHCP(String contractNumber) {
return contractRepository.findContractByExpiredDate(contractNumber) != null ? true : false;
}
private String checkIsFullyPaid(String contractNumber) {
return contractRepository.getFullyPaid(contractNumber);
}
@Override
public List<Contract> checkPgwContract(List<Contract> contractList) {
for (Contract contract : contractList) {
//check paymentType
if (contract.getPaymentType() != null &&
contract.getPaymentType().equals(PAYMENT_TYPE_HCP)) {
if (checkHCP(contract.getContractNumber())) {
//check isFullyPaid
if (checkIsFullyPaid(contract.getContractNumber()).equals(FLAG_YES)) {
return new ArrayList<>();
}
} else {
return new ArrayList<>();
}
}
}
return contractList;
}
单元测试
@InjectMocks
@Spy
private ContractServiceImpl service;
@Mock
ContractRepository contractRepository;
@Mock
OasysContractRepository oasysContractRepository;
@Mock
ContractServiceManager serviceManager;
public static final String contractNumber = "3900006835";
@Test
public void getListOfContractBy_hcp_success() {
List<OasysContract> oasysContractList = new ArrayList<>();
oasysContractList.isEmpty();
List<Contract> contractList = new ArrayList<>();
contractList.add(BuildUtil.buildContract());
//mock
Mockito.doReturn(oasysContractList).when(oasysContractRepository).findByContractNumber(contractNumber);
Mockito.doReturn(BuildUtil.buildContractList()).when(contractRepository).findContractsByContractNumber(contractNumber);
Mockito.doReturn(contractList).when(serviceManager).checkPgwContract(contractList);
Mockito.doReturn(BuildUtil.buildContract()).when(contractRepository).findContractByExpiredDate(contractNumber);
Mockito.doReturn("N").when(contractRepository).getFullyPaid(contractNumber);
//test
List<Contract> contracts = service.getListOfContractBy(contractNumber);
System.out.println(contracts);
assert(!contracts.isEmpty());
}
现在,contracts 参数的值为空。应该是return contractList。我认为是因为方法 checkPgwContract 的模拟被忽略了。
我的测试还是会通过,这显然是错误的,那我应该如何测试呢?
【问题讨论】:
-
BuildUtil.buildContractList() 中有什么?
-
您确定您的
contractServiceManager模拟已正确注入您的ContractServiceImpl服务吗?由于您没有为您的类添加构造函数,我假设使用了field injection,但这将要求您的测试中的变量 (serviceManager) 与您的测试类中的变量 (contractServiceManager) 具有相同的名称.
标签: java unit-testing mockito spring-boot-test spy