[英]Spring - Unit Test with Mock - How to mock a Custom Collector in a Service unit test
[英]How to mock service in unit test
例如,我在 FileServiceImpl 中有這個方法:
@Service
public class FileServiceImpl implements FileService {
private final ExecutorService executorService;
private final UploadsService uploadsService;
private final CandidatesService candidatesService;
@Autowired
public FileServiceImpl(ExecutorService executorService, UploadsService uploadsService, CandidatesService candidatesService) {
this.executorService = executorService;
this.uploadsService = uploadsService;
this.candidatesService = candidatesService;
}
@Override
public Upload uploadFile(MultipartFile file) throws IOException {
String filename = file.getOriginalFilename();
if (!filename.endsWith(".xlsx")) {
throw new IOException("File format is not .xlsx");
}
Upload upload = new Upload(UploadStatus.IN_PROGRESS, LocalDateTime.now(), filename);
uploadsService.saveUpload(upload);
executorService.execute(new XLSXAsyncImporter(upload, file.getInputStream(), uploadsService, candidatesService));
return upload;
}
}
我需要如何編寫單元測試? 我已經開始寫這個:
@ExtendWith(MockitoExtension.class)
public class FileServiceImplTest {
@Mock
private ExecutorService executorService;
@Mock
private UploadsService uploadsService;
@Mock
private CandidatesService candidatesService;
private FileServiceImpl fileService;
private Upload upload;
private MockMultipartFile file1, file2;
@BeforeEach
public void setUp() {
fileService = new FileServiceImpl(executorService, uploadsService, candidatesService);
upload = new Upload(UploadStatus.DONE, LocalDateTime.of(2021, 1, 1, 0, 0), "filename");
file1 = new MockMultipartFile("filename 1", "filename.xlsx", "multipart/form-data", "".getBytes());
file2 = new MockMultipartFile("filename 2", "", "multipart/form-data", "".getBytes());
}
我想寫兩個測試:服務方法完成和服務方法拋出 IOException。 拜托,你能幫我寫測試方法嗎? 我覆蓋了測試更簡單的其他服務。 但我很困惑我需要用這個做什么。
首先,如您所想,沒有必要使用真正的ExecutorService
。
這里的重點是測試上傳功能。 如果此功能使用外部服務、對象或其他任何東西,您應該模擬這個軟件的第三方部分。 重點始終是您的代碼和功能。
回到你的代碼,我將測試三個方面:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.