java - 如何模拟某种类型的列表
问题描述
我有控制器,它将 List 作为帖子正文
User getYoungestUser (int id,@Valid @RequestBody List<User> requests)
{
//somelogic and returns a user
return requests.stream().min(Comparator.comparing(x-> x.getAge())).get();
}
我只是想嘲笑
Mockito.when(service.getYoungestUser(anyInt(),anyList()))
.thenReturn(Collections.singletonList(new User()));
而不是anyList,我想使用像anyList(User.class) 或any(List< User >.class)这样的用户类型列表,编译器当然不接受它们,它在模拟期间严格检查列表的类型
我从其他链接获得了以下内容,但无法弄清楚如何在代码中使用它。
@SuppressWarnings( "unchecked" )
List<User> mocked1 = mock(List.class);
我尝试了以下三种方法,但都没有奏效。请提出一种使用方法
//throws compiling error
Mockito.when(service.getYoungestUser(anyInt(),any(mocked1)))
.thenReturn(Collections.singletonList(new User()));
//not working as it treats first parameter is expression and
//second param is a value and throws error after running the test
Mockito.when(anyInt(),service.getYoungestUser(anyInt(),mocked1)))
.thenReturn(Collections.singletonList(new User()));
//wont work as eq() is used for different purpose,yet just gave a try, The mock
//doesnt work
Mockito.when(anyInt(),service.getYoungestUser(anyInt(),eq(mocked1))))
.thenReturn(Collections.singletonList(new User()));
解决方案
以下应该可以解决问题:
Mockito.when(service.getYoungestUser(anyInt(), ArgumentMatchers.<List<User>>anyList()))
.thenReturn(Collections.singletonList(new User()));
推荐阅读
- api - 如何为 vue.js 应用程序提供公共 API?
- javascript - d3js获取矩形的角坐标
- reactjs - React: Uncaught ReferenceError: Autocomplete is not defined 即使导入了 js 库
- java - Clock.systemUTC() 和 Clock.systemDefaultZone() 有什么区别?
- xml - 如何(以及使用哪种工具)在 Azure 中发送 Soap 请求(数据工厂、逻辑应用程序、API 管理......)
- xamarin - Xamarin-Nsurlsession UploadTask 在后台不适用于 iOS
- go - 为什么我在尝试从从未在 goroutine 中接收数据但在 main func 中接收数据的通道中读取时不会出现死锁
- macos - 从原始 PDF 文本恢复被 Mac 的 Preview 应用程序损坏的 PDF 中的注释
- python - 在 QPlainTextEdit 元素中使用 Shift+Return 的 QShortcut 和 QKeySequence
- android - 模拟器无法启动(c066d201:未处理的退出 1d)