【问题标题】:How to mock service in unit test如何在单元测试中模拟服务
【发布时间】:2021-10-10 19:34:05
【问题描述】:

比如我在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。使用真实的。
  • @Louis Wasserman,感谢您的建议。但为什么?我不必使用executorService.execute签入测试方法吗?你能解释一下为什么我不应该嘲笑它吗?我想了解如何正确编写测试。
  • 不,你为什么要这样做?这是一个实现细节。您应该尽可能在测试中使用真实类型,并且只对设置成本高昂的东西使用模拟。
  • 那是因为我们团队现在有这种类型的测试,所以我需要这样做——这是我的任务

标签: java spring unit-testing junit mockito


【解决方案1】:

首先,如你所想,没有必要使用真正的ExecutorService

这里的重点是测试上传功能。如果此功能使用外部服务、对象或其他任何东西,您应该模拟这个软件的第三部分。重点始终是您的代码、您的功能。

回到你的代码,我会测试三个方面:

  1. 文件验证
  2. 对上传服务的调用
  3. 提交到执行器服务

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-18
    • 2016-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2020-03-22
    • 1970-01-01
    相关资源
    最近更新 更多