java - 如何使用 Mockito 模拟 Api 包装器上的一系列调用
问题描述
我是 Mocking 和测试的新手,我似乎无法弄清楚我需要做什么来测试这个 api 包装器。我有一个类可以从 Spotify api 调用中获取曲目列表。我正在使用这个包https://github.com/thelinmichael/spotify-web-api-java/
我模拟了 SpotifyApi 类,以便在单元测试期间它实际上不会调用 api。但是为了获得结果,我需要进行一系列调用,每个调用都返回一个不同的类。我尝试嘲笑每个班级并将它们用作其他人的回报,但这会导致问题。我不仅需要知道每个类的细分,而且在这个流程中,一些类是我无法模拟的最终类。 SearchTracksRequest.Builder特别是最终类,因此模拟失败。
感觉我对此采取了错误的方法,因为它看起来很简单,很常见,但我不知道如何让它可测试。我是否以正确的方式解决这个问题,我应该如何为此编写测试?
这是我要测试的代码
班上
public class Spotify {
private SpotifyApi spotify;
public Spotify(SpotifyApi spotify) {
this.spotify = spotify;
}
public Track[] browse(String search) throws ParseException, SpotifyWebApiException, IOException {
return spotify.searchTracks(search)
.build()
.execute()
.getItems();
}
}
测试班
class SpotifyTest {
@Test
public void test_spotify_can_browse() throws ParseException, SpotifyWebApiException, IOException {
Track[] Exptracks = new Track[0];
SpotifyApi mockSpotify = mock(SpotifyApi.class);
SearchTracksRequest.Builder mockBuilder = mock(SearchTracksRequest.Builder.class);
SearchTracksRequest mockRequest = mock(SearchTracksRequest.class);
@SuppressWarnings("unchecked")
Paging<Track> mockExecute = (Paging<Track>) mock(Paging.class);
when(mockSpotify.searchTracks("Spirit Of Radio")).thenReturn(mockBuilder);
when(mockBuilder.build()).thenReturn(mockRequest);
when(mockRequest.execute()).thenReturn(mockExecute);
when(mockExecute.getItems()).thenReturn(Exptracks);
Track[] tracks = new Spotify(mockSpotify).browse("Spirit Of Radio");
assertEquals(tracks, Exptracks);
}
}
解决方案
推荐阅读
- .net - Visual Studio SSDT 数据库项目 (.sqlproj) 构建 - 使用没有 MSBUILD (msbuild.exe) 的 CLI 生成 .dacpac
- flutter - 如何在颤动中更改另一个类的字段值?
- flutter - 在使用 Streambuilder 从 firebase 实时数据库获取数据(子子键)时,数据在保存时不按顺序排列
- c# - cshtml页面显示变量名而不是值
- git - $(NugetPackageRoot) 宏在 VS2019 中自动更改为 *.sfproj 文件中的“..\packages\....”,在推送到 Git 之前不断需要撤消更改
- python - OpenCV(4.1.2) 错误: (-215:Assertion failed) !ssize.empty() in function 'cv::resize'
- arrays - 如何迭代对象数组?
- c# - 在 XAML 中可视化 ObservaleCollection 属性
- .net-core - 使用 microsoft DI 的运行时构造函数参数
- python - 如何将文本文件中由:分隔的字符串和数字拆分为python中的行和列