首页 > 解决方案 > 如何使用 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);

    }

}

标签: javajunitmockito

解决方案


推荐阅读