retrofit.client.Request Java Examples

The following examples show how to use retrofit.client.Request. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Ok3Client.java    From retrofit1-okhttp3-client with Apache License 2.0 6 votes vote down vote up
static okhttp3.Request createRequest(Request request) {
  RequestBody requestBody;
  if (requiresRequestBody(request.getMethod()) && request.getBody() == null) {
    requestBody = RequestBody.create(null, NO_BODY);
  } else {
    requestBody = createRequestBody(request.getBody());
  }

  okhttp3.Request.Builder builder = new okhttp3.Request.Builder()
      .url(request.getUrl())
      .method(request.getMethod(), requestBody);

  List<Header> headers = request.getHeaders();
  for (int i = 0, size = headers.size(); i < size; i++) {
    Header header = headers.get(i);
    String value = header.getValue();
    if (value == null) {
      value = "";
    }
    builder.addHeader(header.getName(), value);
  }

  return builder.build();
}
 
Example #2
Source File: SpotifyServiceTest.java    From spotify-web-api-android with MIT License 6 votes vote down vote up
@Test
public void shouldCheckFollowingUsers() throws IOException {
    Type modelType = new TypeToken<List<Boolean>>() {
    }.getType();
    String body = TestUtils.readTestData("follow_is_following_users.json");
    List<Boolean> fixture = mGson.fromJson(body, modelType);

    final String userIds = "thelinmichael,wizzler";

    Response response = TestUtils.getResponseFromModel(fixture, modelType);

    when(mMockClient.execute(argThat(new ArgumentMatcher<Request>() {
        @Override
        public boolean matches(Object argument) {
            try {
                return ((Request) argument).getUrl().contains("type=user") &&
                        ((Request) argument).getUrl().contains("ids=" + URLEncoder.encode(userIds, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                return false;
            }
        }
    }))).thenReturn(response);

    Boolean[] result = mSpotifyService.isFollowingUsers(userIds);
    this.compareJSONWithoutNulls(body, result);
}
 
Example #3
Source File: SpotifyServiceTest.java    From spotify-web-api-android with MIT License 6 votes vote down vote up
@Test
public void shouldCheckFollowingArtists() throws IOException {
    Type modelType = new TypeToken<List<Boolean>>() {
    }.getType();
    String body = TestUtils.readTestData("follow_is_following_artists.json");
    List<Boolean> fixture = mGson.fromJson(body, modelType);

    final String artistIds = "3mOsjj1MhocRVwOejIZlTi";

    Response response = TestUtils.getResponseFromModel(fixture, modelType);

    when(mMockClient.execute(argThat(new ArgumentMatcher<Request>() {
        @Override
        public boolean matches(Object argument) {
            try {
                return ((Request) argument).getUrl().contains("type=artist") &&
                        ((Request) argument).getUrl().contains("ids=" + URLEncoder.encode(artistIds, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                return false;
            }
        }
    }))).thenReturn(response);

    Boolean[] result = mSpotifyService.isFollowingArtists(artistIds);
    this.compareJSONWithoutNulls(body, result);
}
 
Example #4
Source File: SpotifyServiceTest.java    From spotify-web-api-android with MIT License 6 votes vote down vote up
@Test
public void shouldCheckFollowedArtists() throws IOException {

    String body = TestUtils.readTestData("followed-artists.json");
    ArtistsCursorPager fixture = mGson.fromJson(body, ArtistsCursorPager.class);

    Response response = TestUtils.getResponseFromModel(fixture, ArtistsCursorPager.class);
    when(mMockClient.execute(argThat(new ArgumentMatcher<Request>() {
        @Override
        public boolean matches(Object argument) {
            return ((Request) argument).getUrl().contains("type=artist");
        }
    }))).thenReturn(response);

    ArtistsCursorPager result = mSpotifyService.getFollowedArtists();
    compareJSONWithoutNulls(body, result);
}
 
Example #5
Source File: RequestBuilder.java    From android-discourse with Apache License 2.0 6 votes vote down vote up
Request build() throws UnsupportedEncodingException {
    String apiUrl = this.apiUrl;

    StringBuilder url = new StringBuilder(apiUrl);
    if (apiUrl.endsWith("/")) {
        // We require relative paths to start with '/'. Prevent a double-slash.
        url.deleteCharAt(url.length() - 1);
    }

    url.append(relativeUrl);

    StringBuilder queryParams = this.queryParams;
    if (queryParams.length() > 0) {
        url.append(queryParams);
    }

    if (multipartBody != null && multipartBody.getPartCount() == 0) {
        throw new IllegalStateException("Multipart requests must contain at least one part.");
    }

    return new Request(requestMethod, url.toString(), headers, body);
}
 
Example #6
Source File: Ok3ClientTest.java    From retrofit1-okhttp3-client with Apache License 2.0 6 votes vote down vote up
@Test public void emptyResponse() throws IOException {
  okhttp3.Response okResponse = new okhttp3.Response.Builder()
      .code(200)
      .message("OK")
      .body(new TestResponseBody("", null))
      .addHeader("foo", "bar")
      .addHeader("kit", "kat")
      .protocol(Protocol.HTTP_1_1)
      .request(new okhttp3.Request.Builder()
          .url(HOST + "/foo/bar/")
          .get()
          .build())
      .build();
  Response response = Ok3Client.parseResponse(okResponse);

  assertThat(response.getUrl()).isEqualTo(HOST + "/foo/bar/");
  assertThat(response.getStatus()).isEqualTo(200);
  assertThat(response.getReason()).isEqualTo("OK");
  assertThat(response.getHeaders()) //
      .containsExactly(new Header("foo", "bar"), new Header("kit", "kat"));
  assertThat(response.getBody()).isNull();
}
 
Example #7
Source File: Ok3ClientTest.java    From retrofit1-okhttp3-client with Apache License 2.0 6 votes vote down vote up
@Test public void responseNoContentType() throws IOException {
  okhttp3.Response okResponse = new okhttp3.Response.Builder()
      .code(200).message("OK")
      .body(new TestResponseBody("hello", null))
      .addHeader("foo", "bar")
      .addHeader("kit", "kat")
      .protocol(Protocol.HTTP_1_1)
      .request(new okhttp3.Request.Builder()
          .url(HOST + "/foo/bar/")
          .get()
          .build())
      .build();
  Response response = Ok3Client.parseResponse(okResponse);

  assertThat(response.getUrl()).isEqualTo(HOST + "/foo/bar/");
  assertThat(response.getStatus()).isEqualTo(200);
  assertThat(response.getReason()).isEqualTo("OK");
  assertThat(response.getHeaders()) //
      .containsExactly(new Header("foo", "bar"), new Header("kit", "kat"));
  TypedInput responseBody = response.getBody();
  assertThat(responseBody.mimeType()).isNull();
  assertThat(buffer(source(responseBody.in())).readUtf8()).isEqualTo("hello");
}
 
Example #8
Source File: Ok3ClientTest.java    From retrofit1-okhttp3-client with Apache License 2.0 6 votes vote down vote up
@Test public void post() throws IOException {
  TypedString body = new TypedString("hi");
  Request request = new Request("POST", HOST + "/foo/bar/", null, body);
  okhttp3.Request okRequest = Ok3Client.createRequest(request);

  assertThat(okRequest.method()).isEqualTo("POST");
  assertThat(okRequest.url().toString()).isEqualTo(HOST + "/foo/bar/");
  assertThat(okRequest.headers().size()).isEqualTo(0);

  RequestBody okBody = okRequest.body();
  assertThat(okBody).isNotNull();

  Buffer buffer = new Buffer();
  okBody.writeTo(buffer);
  assertThat(buffer.readUtf8()).isEqualTo("hi");
}
 
Example #9
Source File: Ok3Client.java    From retrofit1-okhttp3-client with Apache License 2.0 6 votes vote down vote up
static okhttp3.Request createRequest(Request request) {
  RequestBody requestBody;
  if (requiresRequestBody(request.getMethod()) && request.getBody() == null) {
    requestBody = RequestBody.create(null, NO_BODY);
  } else {
    requestBody = createRequestBody(request.getBody());
  }

  okhttp3.Request.Builder builder = new okhttp3.Request.Builder()
      .url(request.getUrl())
      .method(request.getMethod(), requestBody);

  List<Header> headers = request.getHeaders();
  for (int i = 0, size = headers.size(); i < size; i++) {
    Header header = headers.get(i);
    String value = header.getValue();
    if (value == null) {
      value = "";
    }
    builder.addHeader(header.getName(), value);
  }

  return builder.build();
}
 
Example #10
Source File: SpotifyServiceTest.java    From spotify-web-api-android with MIT License 6 votes vote down vote up
@Test
public void shouldFollowAPlaylist() throws Exception {
    final Type modelType = new TypeToken<Result>() {}.getType();
    final String body = ""; // Returns empty body
    final Result fixture = mGson.fromJson(body, modelType);

    final Response response = TestUtils.getResponseFromModel(fixture, modelType);

    final String owner = "thelinmichael";
    final String playlistId = "4JPlPnLULieb2WPFKlLiRq";

    when(mMockClient.execute(argThat(new ArgumentMatcher<Request>() {
        @Override
        public boolean matches(Object argument) {
            final Request request = (Request) argument;
            return request.getUrl().endsWith(String.format("/users/%s/playlists/%s/followers",
                    owner, playlistId)) &&
                    "PUT".equals(request.getMethod());
        }
    }))).thenReturn(response);

    final Result result = mSpotifyService.followPlaylist(owner, playlistId);
    this.compareJSONWithoutNulls(body, result);
}
 
Example #11
Source File: Ok3ClientTest.java    From retrofit1-okhttp3-client with Apache License 2.0 6 votes vote down vote up
@Test public void post() throws IOException {
  TypedString body = new TypedString("hi");
  Request request = new Request("POST", HOST + "/foo/bar/", null, body);
  okhttp3.Request okRequest = Ok3Client.createRequest(request);

  assertThat(okRequest.method()).isEqualTo("POST");
  assertThat(okRequest.url().toString()).isEqualTo(HOST + "/foo/bar/");
  assertThat(okRequest.headers().size()).isEqualTo(0);

  RequestBody okBody = okRequest.body();
  assertThat(okBody).isNotNull();

  Buffer buffer = new Buffer();
  okBody.writeTo(buffer);
  assertThat(buffer.readUtf8()).isEqualTo("hi");
}
 
Example #12
Source File: ConnectivityAwareUrlClient.java    From MVPAndroidBootstrap with Apache License 2.0 6 votes vote down vote up
@Override
public Response execute(Request request) throws IOException {
    try {
        if (!ConnectivityUtil.isConnected(context)) {
            throw RetrofitError.unexpectedError("Nincs internet", new NoConnectivityException("No Internet"));
        } else {

            Response r = wrappedClient.execute(request);

            checkResult(r);

            return r;
        }
    } catch (RetrofitError retrofitError) {
        if (retry(retrofitError, retries)) {
            return execute(request);
        } else {
            throw new ConnectionError();
        }
    } catch (Exception e) {
        throw new ConnectionError();
    }
}
 
Example #13
Source File: Ok3ClientTest.java    From retrofit1-okhttp3-client with Apache License 2.0 6 votes vote down vote up
@Test public void emptyResponse() throws IOException {
  okhttp3.Response okResponse = new okhttp3.Response.Builder()
      .code(200)
      .message("OK")
      .body(new TestResponseBody("", null))
      .addHeader("foo", "bar")
      .addHeader("kit", "kat")
      .protocol(Protocol.HTTP_1_1)
      .request(new okhttp3.Request.Builder()
          .url(HOST + "/foo/bar/")
          .get()
          .build())
      .build();
  Response response = Ok3Client.parseResponse(okResponse);

  assertThat(response.getUrl()).isEqualTo(HOST + "/foo/bar/");
  assertThat(response.getStatus()).isEqualTo(200);
  assertThat(response.getReason()).isEqualTo("OK");
  assertThat(response.getHeaders()) //
      .containsExactly(new Header("foo", "bar"), new Header("kit", "kat"));
  assertThat(response.getBody()).isNull();
}
 
Example #14
Source File: Ok3ClientTest.java    From retrofit1-okhttp3-client with Apache License 2.0 6 votes vote down vote up
@Test public void responseNoContentType() throws IOException {
  okhttp3.Response okResponse = new okhttp3.Response.Builder()
      .code(200).message("OK")
      .body(new TestResponseBody("hello", null))
      .addHeader("foo", "bar")
      .addHeader("kit", "kat")
      .protocol(Protocol.HTTP_1_1)
      .request(new okhttp3.Request.Builder()
          .url(HOST + "/foo/bar/")
          .get()
          .build())
      .build();
  Response response = Ok3Client.parseResponse(okResponse);

  assertThat(response.getUrl()).isEqualTo(HOST + "/foo/bar/");
  assertThat(response.getStatus()).isEqualTo(200);
  assertThat(response.getReason()).isEqualTo("OK");
  assertThat(response.getHeaders()) //
      .containsExactly(new Header("foo", "bar"), new Header("kit", "kat"));
  TypedInput responseBody = response.getBody();
  assertThat(responseBody.mimeType()).isNull();
  assertThat(buffer(source(responseBody.in())).readUtf8()).isEqualTo("hello");
}
 
Example #15
Source File: SpotifyServiceTest.java    From spotify-web-api-android with MIT License 6 votes vote down vote up
@Test
public void shouldParseErrorResponse() throws Exception {
    final String body = TestUtils.readTestData("error-unauthorized.json");
    final ErrorResponse fixture = mGson.fromJson(body, ErrorResponse.class);

    final Response response = TestUtils.getResponseFromModel(403, fixture, ErrorResponse.class);

    when(mMockClient.execute(isA(Request.class))).thenReturn(response);

    boolean errorReached = false;

    try {
        mSpotifyService.getMySavedTracks();
    } catch (RetrofitError error) {
        errorReached = true;

        SpotifyError spotifyError = SpotifyError.fromRetrofitError(error);
        assertEquals(fixture.error.status, spotifyError.getErrorDetails().status);
        assertEquals(fixture.error.message, spotifyError.getErrorDetails().message);
        assertEquals(403, spotifyError.getRetrofitError().getResponse().getStatus());
    }

    assertTrue(errorReached);
}
 
Example #16
Source File: SpotifyServiceTest.java    From spotify-web-api-android with MIT License 5 votes vote down vote up
@Test
public void shouldGetPlaylistFollowersContains() throws IOException {
    final Type modelType = new TypeToken<List<Boolean>>() {
    }.getType();
    final String body = TestUtils.readTestData("playlist-followers-contains.json");
    final List<Boolean> fixture = mGson.fromJson(body, modelType);

    final Response response = TestUtils.getResponseFromModel(fixture, modelType);

    final String userIds = "thelinmichael,jmperezperez,kaees";

    when(mMockClient.execute(argThat(new ArgumentMatcher<Request>() {
        @Override
        public boolean matches(Object argument) {
            try {
                return ((Request) argument).getUrl()
                        .contains("ids=" + URLEncoder.encode(userIds, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                return false;
            }
        }
    }))).thenReturn(response);

    final String requestPlaylist = TestUtils.readTestData("playlist-response.json");
    final Playlist requestFixture = mGson.fromJson(requestPlaylist, Playlist.class);

    final Boolean[] result = mSpotifyService.areFollowingPlaylist(requestFixture.owner.id, requestFixture.id, userIds);
    this.compareJSONWithoutNulls(body, result);
}
 
Example #17
Source File: SpotifyServiceTest.java    From spotify-web-api-android with MIT License 5 votes vote down vote up
@Test
public void shouldGetCurrentUserData() throws IOException {
    String body = TestUtils.readTestData("current-user.json");
    UserPrivate fixture = mGson.fromJson(body, UserPrivate.class);

    Response response = TestUtils.getResponseFromModel(fixture, UserPrivate.class);
    when(mMockClient.execute(Matchers.<Request>any())).thenReturn(response);

    UserPrivate userPrivate = mSpotifyService.getMe();
    this.compareJSONWithoutNulls(body, userPrivate);
}
 
Example #18
Source File: SpotifyServiceTest.java    From spotify-web-api-android with MIT License 5 votes vote down vote up
public boolean matches(Object request) {
    try {
        return ((Request) request).getUrl().contains(URLEncoder.encode(mId, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        return false;
    }
}
 
Example #19
Source File: SpotifyServiceTest.java    From spotify-web-api-android with MIT License 5 votes vote down vote up
@Test
public void shouldGetCurrentUserPlaylists() throws Exception {
    final Type modelType = new TypeToken<Pager<PlaylistSimple>>() {}.getType();
    String body = TestUtils.readTestData("user-playlists.json");
    Pager<PlaylistSimple> fixture = mGson.fromJson(body, modelType);

    Response response = TestUtils.getResponseFromModel(fixture, modelType);
    when(mMockClient.execute(isA(Request.class))).thenReturn(response);

    Pager<PlaylistSimple> playlists = mSpotifyService.getMyPlaylists();
    compareJSONWithoutNulls(body, playlists);
}
 
Example #20
Source File: SpotifyServiceTest.java    From spotify-web-api-android with MIT License 5 votes vote down vote up
@Test
public void shouldGetSearchedTracks() throws IOException {
    String body = TestUtils.readTestData("search-track.json");
    TracksPager fixture = mGson.fromJson(body, TracksPager.class);

    Response response = TestUtils.getResponseFromModel(fixture, TracksPager.class);
    when(mMockClient.execute(isA(Request.class))).thenReturn(response);

    TracksPager tracks = mSpotifyService.searchTracks("Christmas");
    compareJSONWithoutNulls(body, tracks);
}
 
Example #21
Source File: SpotifyServiceTest.java    From spotify-web-api-android with MIT License 5 votes vote down vote up
@Test
public void shouldGetSearchedAlbums() throws IOException {
    String body = TestUtils.readTestData("search-album.json");
    AlbumsPager fixture = mGson.fromJson(body, AlbumsPager.class);

    Response response = TestUtils.getResponseFromModel(fixture, AlbumsPager.class);
    when(mMockClient.execute(isA(Request.class))).thenReturn(response);

    AlbumsPager result = mSpotifyService.searchAlbums("Christmas");
    compareJSONWithoutNulls(body, result);
}
 
Example #22
Source File: SpotifyServiceTest.java    From spotify-web-api-android with MIT License 5 votes vote down vote up
@Test
public void shouldGetSearchedArtists() throws IOException {
    String body = TestUtils.readTestData("search-artist.json");
    ArtistsPager fixture = mGson.fromJson(body, ArtistsPager.class);

    Response response = TestUtils.getResponseFromModel(fixture, ArtistsPager.class);
    when(mMockClient.execute(isA(Request.class))).thenReturn(response);

    ArtistsPager result = mSpotifyService.searchArtists("Christmas");
    compareJSONWithoutNulls(body, result);
}
 
Example #23
Source File: SpotifyServiceTest.java    From spotify-web-api-android with MIT License 5 votes vote down vote up
@Test
public void shouldGetSearchedPlaylists() throws IOException {
    String body = TestUtils.readTestData("search-playlist.json");
    PlaylistsPager fixture = mGson.fromJson(body, PlaylistsPager.class);

    Response response = TestUtils.getResponseFromModel(fixture, PlaylistsPager.class);
    when(mMockClient.execute(isA(Request.class))).thenReturn(response);

    PlaylistsPager result = mSpotifyService.searchPlaylists("Christmas");
    compareJSONWithoutNulls(body, result);
}
 
Example #24
Source File: SpotifyServiceTest.java    From spotify-web-api-android with MIT License 5 votes vote down vote up
@Test
public void shouldGetCategories() throws Exception {
    final Type modelType = new TypeToken<CategoriesPager>() {
    }.getType();
    final String body = TestUtils.readTestData("get-categories.json");
    final CategoriesPager fixture = mGson.fromJson(body, modelType);

    final Response response = TestUtils.getResponseFromModel(fixture, modelType);

    final String country = "SE";
    final String locale = "sv_SE";
    final int offset = 1;
    final int limit = 2;

    when(mMockClient.execute(argThat(new ArgumentMatcher<Request>() {
        @Override
        public boolean matches(Object argument) {
            String requestUrl = ((Request) argument).getUrl();
            return requestUrl.contains(String.format("limit=%d", limit)) &&
                    requestUrl.contains(String.format("offset=%d", offset)) &&
                    requestUrl.contains(String.format("country=%s", country)) &&
                    requestUrl.contains(String.format("locale=%s", locale));
        }
    }))).thenReturn(response);


    final Map<String, Object> options = new HashMap<String, Object>();
    options.put("offset", offset);
    options.put("limit", limit);
    options.put("country", country);
    options.put("locale", locale);

    final CategoriesPager result = mSpotifyService.getCategories(options);
    this.compareJSONWithoutNulls(body, result);
}
 
Example #25
Source File: SpotifyServiceTest.java    From spotify-web-api-android with MIT License 5 votes vote down vote up
@Test
public void shouldGetCategory() throws Exception {
    final Type modelType = new TypeToken<Category>() {
    }.getType();
    final String body = TestUtils.readTestData("category.json");
    final Category fixture = mGson.fromJson(body, modelType);

    final Response response = TestUtils.getResponseFromModel(fixture, modelType);

    final String categoryId = "mood";
    final String country = "SE";
    final String locale = "sv_SE";

    when(mMockClient.execute(argThat(new ArgumentMatcher<Request>() {
        @Override
        public boolean matches(Object argument) {
            String requestUrl = ((Request) argument).getUrl();
            return requestUrl.contains(String.format("locale=%s", locale)) &&
                    requestUrl.contains(String.format("country=%s", country));

        }
    }))).thenReturn(response);

    final Map<String, Object> options = new HashMap<String, Object>();
    options.put("country", country);
    options.put("locale", locale);

    final Category result = mSpotifyService.getCategory(categoryId, options);
    this.compareJSONWithoutNulls(body, result);
}
 
Example #26
Source File: SpotifyServiceTest.java    From spotify-web-api-android with MIT License 5 votes vote down vote up
@Test
public void shouldGetUserPlaylists() throws Exception {
    final Type modelType = new TypeToken<Pager<PlaylistSimple>>() {}.getType();
    String body = TestUtils.readTestData("user-playlists.json");
    Pager<PlaylistSimple> fixture = mGson.fromJson(body, modelType);

    Response response = TestUtils.getResponseFromModel(fixture, modelType);
    when(mMockClient.execute(isA(Request.class))).thenReturn(response);

    Pager<PlaylistSimple> playlists = mSpotifyService.getPlaylists("test");
    compareJSONWithoutNulls(body, playlists);
}
 
Example #27
Source File: SpotifyServiceTest.java    From spotify-web-api-android with MIT License 5 votes vote down vote up
@Test
public void shouldGetPlaylistsForCategory() throws Exception {
    final Type modelType = new TypeToken<PlaylistsPager>() {
    }.getType();
    final String body = TestUtils.readTestData("category-playlist.json");
    final PlaylistsPager fixture = mGson.fromJson(body, modelType);

    final Response response = TestUtils.getResponseFromModel(fixture, modelType);

    final String categoryId = "mood";
    final String country = "SE";
    final int offset = 1;
    final int limit = 2;

    when(mMockClient.execute(argThat(new ArgumentMatcher<Request>() {
        @Override
        public boolean matches(Object argument) {
            String requestUrl = ((Request) argument).getUrl();
            return requestUrl.contains(String.format("limit=%d", limit)) &&
                    requestUrl.contains(String.format("offset=%d", offset)) &&
                    requestUrl.contains(String.format("country=%s", country));
        }
    }))).thenReturn(response);

    final Map<String, Object> options = new HashMap<String, Object>();
    options.put("country", country);
    options.put("offset", offset);
    options.put("limit", limit);

    final PlaylistsPager result = mSpotifyService.getPlaylistsForCategory(categoryId, options);
    this.compareJSONWithoutNulls(body, result);
}
 
Example #28
Source File: SpotifyServiceTest.java    From spotify-web-api-android with MIT License 5 votes vote down vote up
@Test
public void shouldGetArtistRelatedArtists() throws Exception {
    String body = TestUtils.readTestData("artist-related-artists.json");
    Artists fixture = mGson.fromJson(body, Artists.class);

    Response response = TestUtils.getResponseFromModel(fixture, Artists.class);
    when(mMockClient.execute(isA(Request.class))).thenReturn(response);

    Artists tracks = mSpotifyService.getRelatedArtists("test");
    compareJSONWithoutNulls(body, tracks);
}
 
Example #29
Source File: SpotifyServiceTest.java    From spotify-web-api-android with MIT License 5 votes vote down vote up
@Test
public void shouldGetArtistTopTracksTracks() throws Exception {
    String body = TestUtils.readTestData("tracks-for-artist.json");
    Tracks fixture = mGson.fromJson(body, Tracks.class);

    Response response = TestUtils.getResponseFromModel(fixture, Tracks.class);
    when(mMockClient.execute(isA(Request.class))).thenReturn(response);

    Tracks tracks = mSpotifyService.getArtistTopTrack("test", "SE");
    compareJSONWithoutNulls(body, tracks);
}
 
Example #30
Source File: SpotifyServiceTest.java    From spotify-web-api-android with MIT License 5 votes vote down vote up
@Test
public void shouldGetNewReleases() throws IOException {
    final String countryId = "SE";
    final int limit = 5;

    String body = TestUtils.readTestData("new-releases.json");
    NewReleases fixture = mGson.fromJson(body, NewReleases.class);

    Response response = TestUtils.getResponseFromModel(fixture, NewReleases.class);

    when(mMockClient.execute(argThat(new ArgumentMatcher<Request>() {
        @Override
        public boolean matches(Object argument) {

            try {
                return ((Request) argument).getUrl().contains("limit=" + limit) &&
                        ((Request) argument).getUrl().contains("country=" + URLEncoder.encode(countryId, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                return false;
            }
        }
    }))).thenReturn(response);

    Map<String, Object> options = new HashMap<String, Object>();
    options.put(SpotifyService.COUNTRY, countryId);
    options.put(SpotifyService.OFFSET, 0);
    options.put(SpotifyService.LIMIT, limit);
    NewReleases newReleases = mSpotifyService.getNewReleases(options);

    this.compareJSONWithoutNulls(body, newReleases);
}