spring-boot - 如何在 jupiter Spring Boot 中使用 any()?
问题描述
我正在尝试测试用于检索书籍的控制器方法。出于某种原因,我想用下面的 when() 方法模拟的 uploadBook() 不返回对象。
@Test
void uploadNewBookTest() {
MockMultipartFile firstFile = new MockMultipartFile("book", "filename.txt", "text/plain", "some xml".getBytes());
Author author = new Author("John", "Doe", "john.doe@mail.ru");
BookDto bookDto = new BookDto("some title", "desc", "en-US", "Sci-Fi", "pdf", "2020-12-10", author.getEmail(), "sdd23421");
Mockito.when(bookUploadService.uploadBook(bookDto, firstFile))
.thenReturn(Optional.of(bookDto));
try {
mockMvc.perform(
MockMvcRequestBuilders.multipart("/books")
.file(firstFile)
.param("title", bookDto.getTitle())
.param("shortDescription", "asdf")
.param("publishedDate", bookDto.getPublishedDate())
.param("language", bookDto.getLanguage())
.param("genre", bookDto.getGenre())
.param("email", "hell")
)
.andExpect(status().isOk());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
为了让 .when() 查看匹配项并返回一个对象模拟对象,我想使用 any(Object.class) 但它似乎在 Jupiter5 中不起作用,就像在 JUnit4 中一样
我想做类似下面的事情
Mockito.when(bookUploadService.uploadBook(any(BookDto.class), any(MultipartFile.class)))
.thenReturn(Optional.of(bookDto));
但是,它要求我将 any() 转换为该方法请求的参数。当我这样做并执行时,它会引发一个强制转换异常。
谁能帮助并告诉我我做错了什么或我错过了什么?或者,如果您明白为什么我的 .when() 没有看到匹配项,那将不胜感激。
这是我试图模拟的方法
public Optional<BookDto> uploadBook(BookDto bookDto, MultipartFile bookFile)
谢谢
解决方案
any(Class<T> type)
是一个普通的模仿功能。
在编译时和运行时,它不能被 JUnit 破坏。因此,当您为测试类正确设置 Spring 单元测试配置时,
使用 JUnit4 或 JUnit 5 不应改变行为,该配置是 JUnit 4 中兼容的 Spring Runner 和 JUnit 5 中兼容的 Spring Extension。
此外,您的原始代码在mocking with在你的单元测试中设置了一些弱点。
关于您当前的问题,我敢打赌您在某处使用了错误的导入,可能是针对. 它应该是静态的;any()
any()
any()
org.mockito.ArgumentMatchers.any
推荐阅读
- java - 在 Spring 5.0.7.RELEASE 中模拟静态方法
- javascript - 单击父组件上的按钮时如何将数据从子组件传递到父组件
- python - 对使用 python Decimal 包的金融应用程序中的浮点精度损失感到困惑
- python - 在两个数组中查找重复值,Python
- java - 从 GitLab-CI 中的 docker 容器中提取测试覆盖率
- datastage - 在指定时间中止 Datastage 作业
- google-cloud-platform - 我被授予存储权限的服务帐户没有 storage.objects.list 访问 Google Cloud Storage 存储桶的权限
- swift - 如何使用 SwiftUI 中的按钮从数组中删除项目?
- javascript - 当表单发送的值与下拉列表中出现的值不同时,获取选择下拉列表的值
- python-3.x - json到python中规范请求的url编码