为Spring Boot服务方法编写单元测试,但无法通过。我是前端开发人员,所以我对Java的单元测试不是很熟悉。 multipartFile是让我最困惑的地方,也是完成整个Junit测试的地方。
Junit4具有模拟单元测试。尝试使用stackoverflow和google进行潜在的更正。
合同服务
@Slf4j
@Service
public class ContractService {
@Autowired
public ContractRepository contractRepository;
@Autowired
public JdbcTemplate jdbcTemplate;
@Autowired
public UserSettingsService userSettingsService;
@Autowired
public ContractPermissionsService contractPermissionsService;
@Autowired
public OCRSubmissionService ocrSubmissionService;
@Autowired
public ContractDocumentStorageService contractDocumentStorageService;
public Contract getContract(int contractID) {
Contract contract = contractRepository.getOne(contractID);
return contract;
}
//TODO: come back and reduce contractID / metaID to one ID.
//TODO: add trigger in DB layer for coterminous
// TODO: make sure isVisible defaults to false
/*
When adding a new contract, the following steps are taken:
1. SQL transaction is begun
2. The meta information is stored, and an ID is generated in SQL.
3. The file is stored with the corresponding document ID.
4. The meta information is updated with the document link.
5. A login, submission, and logoff are made to KTA.
6. As long as all these steps have completed, the transaction is completed
7. Otherwise, the transaction is cancelled ad an error is thrown (controller returns 500)
*/
@Transactional(rollbackFor=Exception.class)
public Contract addNewContract(Contract contract, MultipartFile file) throws Exception {
Contract newContract = this.contractRepository.save(contract);
int ID = contract.getId();
int fileID = this.contractDocumentStorageService.storeFile(file, ID);
contract.setDocumentPathDesc(Integer.toString(fileID));
this.addViewingPermissionsForSubmitter(contract);
Boolean success = this.ocrSubmissionService.SubmitContractForOCR(file, contract.getId());
if(success) {
return this.contractRepository.saveAndFlush(newContract);
} else {
throw new OCRSubmissionFailureException("Error in OCR Submission");
}
}
合同服务测试
public class ContractServiceTest {
ContractService contractServiceUnderTest;
@Before
public void setUp() {
contractServiceUnderTest = new ContractService();
contractServiceUnderTest.contractRepository = mock(ContractRepository.class);
contractServiceUnderTest.jdbcTemplate = mock(JdbcTemplate.class);
contractServiceUnderTest.userSettingsService = mock(UserSettingsService.class);
contractServiceUnderTest.contractPermissionsService = mock(ContractPermissionsService.class);
contractServiceUnderTest.ocrSubmissionService = mock(OCRSubmissionService.class);
contractServiceUnderTest.contractDocumentStorageService = mock(ContractDocumentStorageService.class);
}
@Test
public void testAddNewContract() throws Exception {
// Setup
final Contract contract = new Contract();
final MultipartFile file = null;
final Contract expectedResult = null;
// Run the test
final Contract result = contractServiceUnderTest.addNewContract(contract, file);
// Verify the results
assertEquals(expectedResult, result);
}