Java Code Examples for retrofit2.mock.Calls

The following are top voted examples for showing how to use retrofit2.mock.Calls. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: IFTTTSDK-Android   File: ApiPendingResultTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testExecution() throws Exception {
    ApiPendingResult<Applet> pendingResult = new ApiPendingResult<>(Calls.<Applet>failure(new IOException()),
            new Moshi.Builder().build().adapter(ErrorResponse.class));
    final AtomicReference<ErrorResponse> errorResponseAtomicReference = new AtomicReference<>();
    pendingResult.execute(new PendingResult.ResultCallback<Applet>() {
        @Override
        public void onSuccess(@NonNull Applet result) {
            fail();
        }

        @Override
        public void onFailure(@NonNull ErrorResponse errorResponse) {
            errorResponseAtomicReference.set(errorResponse);
        }
    });

    assertThat(errorResponseAtomicReference.get().code).isEqualTo("exception");
    assertThat(errorResponseAtomicReference.get().message).isEqualTo("Unexpected error");
}
 
Example 2
Project: filestack-java   File: TestImageTransform.java   Source Code and License 6 votes vote down vote up
@Test
public void testStoreExternal() throws Exception {
  String jsonString = "{'url': 'https://cdn.filestackcontent.com/handle'}";
  Gson gson = new Gson();
  StoreResponse storeResponse = gson.fromJson(jsonString, StoreResponse.class);
  String url = "https://example.com/image.jpg";

  Mockito
      .doReturn(Calls.response(storeResponse))
      .when(Networking.getCdnService())
      .transformStoreExt("apiKey", "store", url);

  Config config = new Config("apiKey");
  ImageTransform transform = new ImageTransform(config, url, true);

  Assert.assertNotNull(transform.store());
}
 
Example 3
Project: filestack-java   File: TestClient.java   Source Code and License 6 votes vote down vote up
private static void setupStartMock(UploadService mockUploadService) {
  String jsonString = "{"
      + "'uri' : '/bucket/apikey/filename',"
      + "'region' : 'region',"
      + "'upload_id' : 'id',"
      + "'location_url' : 'url',"
      + "'upload_type' : 'intelligent_ingestion'"
      + "}";

  Gson gson = new Gson();
  StartResponse response = gson.fromJson(jsonString, StartResponse.class);
  Call call = Calls.response(response);
  Mockito
      .doReturn(call)
      .when(mockUploadService)
      .start(Mockito.<String, RequestBody>anyMap());
}
 
Example 4
Project: filestack-java   File: TestClient.java   Source Code and License 6 votes vote down vote up
private static void setupUploadMock(UploadService mockUploadService) {
  String jsonString = "{"
      + "'url' : 'https://s3.amazonaws.com/path',"
      + "'headers' : {"
      + "'Authorization' : 'auth_value',"
      + "'Content-MD5' : 'md5_value',"
      + "'x-amz-content-sha256' : 'sha256_value',"
      + "'x-amz-date' : 'date_value',"
      + "'x-amz-acl' : 'acl_value'"
      + "},"
      + "'location_url' : 'url'"
      + "}";

  Gson gson = new Gson();
  final UploadResponse response = gson.fromJson(jsonString, UploadResponse.class);
  Mockito
      .doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
          return Calls.response(response);
        }
      })
      .when(mockUploadService)
      .upload(Mockito.<String, RequestBody>anyMap());
}
 
Example 5
Project: filestack-java   File: TestClient.java   Source Code and License 6 votes vote down vote up
private static void setupUploadS3Mock(UploadService mockUploadService) {
  MediaType mediaType = MediaType.parse("text/xml");
  ResponseBody responseBody = ResponseBody.create(mediaType, "");
  final Response<ResponseBody> response = Response.success(responseBody,
      Headers.of("ETag", "test-etag"));
  Mockito
      .doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
          return Calls.response(response);
        }
      })
      .when(mockUploadService)
      .uploadS3(Mockito.<String, String>anyMap(), Mockito.anyString(),
          Mockito.any(RequestBody.class));
}
 
Example 6
Project: filestack-java   File: TestClient.java   Source Code and License 6 votes vote down vote up
private static void setupCompleteMock(UploadService mockUploadService) {
  String jsonString = "{"
      + "'handle' : 'handle',"
      + "'url' : 'url',"
      + "'filename' : 'filename',"
      + "'size' : '0',"
      + "'mimetype' : 'mimetype'"
      + "}";

  Gson gson = new Gson();
  CompleteResponse response = gson.fromJson(jsonString, CompleteResponse.class);
  Call call = Calls.response(response);
  Mockito
      .doReturn(call)
      .when(mockUploadService)
      .complete(Mockito.<String, RequestBody>anyMap());
}
 
Example 7
Project: filestack-java   File: TestFileLink.java   Source Code and License 6 votes vote down vote up
@Test
public void testImageSfw() throws Exception {
  Mockito.doAnswer(new Answer() {
    @Override
    public Call<ResponseBody> answer(InvocationOnMock invocation) throws Throwable {
      String handle = invocation.getArgument(1);
      String json = "{'sfw': " + (handle.equals("safe") ? "true" : "false") + "}";
      MediaType mediaType = MediaType.parse("application/json");
      return Calls.response(ResponseBody.create(mediaType, json));
    }
  })
      .when(Networking.getCdnService())
      .transform(Mockito.anyString(), Mockito.anyString());

  Config config = new Config("apiKey", "policy", "signature");

  FileLink safe = new FileLink(config, "safe");
  FileLink notSafe = new FileLink(config, "notSafe");

  Assert.assertTrue(safe.imageSfw());
  Assert.assertFalse(notSafe.imageSfw());
}
 
Example 8
Project: segment-android   File: TransporterTest.java   Source Code and License 6 votes vote down vote up
@Test public void invokesUploadErrorCallback() throws Exception {
  transporter = new Transporter(queue, trackingAPI, callback);

  Message message = new TrackMessage.Builder().userId("userId").event("event").build();
  IOException testException = new IOException("test");

  Call<Void> call = Calls.failure(testException);
  when(trackingAPI.batch(any(Batch.class))).thenReturn(call);

  transporter.enqueue(message).get();

  try {
    transporter.flush().get();
  } catch (ExecutionException e) {
    assertThat(e.getCause()).isEqualTo(testException);
  }
  verify(callback).error(Callback.Event.UPLOAD, message, testException);
}
 
Example 9
Project: quill   File: MockGhostApiService.java   Source Code and License 6 votes vote down vote up
@Override
public Observable<AuthToken> refreshAuthToken(@Body RefreshReqBody credentials) {
    if (credentials.refreshToken.equals("refresh-token")) {
        AuthToken token = new AuthToken();
        token.setAccessToken("refreshed-access-token");
        // token.setRefreshToken("refresh-token");      // refreshed tokens don't have a new refresh token
        token.setCreatedAt(System.currentTimeMillis());
        token.setExpiresIn(60 * 1000);
        return mDelegate
                .returningResponse(token)
                .refreshAuthToken(credentials);
    } else {
        // expired / invalid refresh token
        ResponseBody body = ResponseBody.create(MediaType.parse("application/json"),
                "{\"errors\":[{\"message\":\"Expired or invalid refresh token\",\"errorType\":\"UnauthorizedError\"}]}");
        Response<Object> res = Response.error(401, body);
        return mDelegate
                .returning(Calls.response(res))
                .refreshAuthToken(credentials);
    }
}
 
Example 10
Project: twitter-kit-android   File: OAuth2ServiceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testRequestGuestAuthToken_guestFailure() {

    service.api = new MockOAuth2Api() {
        @Override
        public Call<GuestTokenResponse> getGuestToken(@Header(OAuthConstants.HEADER_AUTHORIZATION) String auth) {
            return Calls.failure(new IOException());
        }
    };

    service.requestGuestAuthToken(new Callback<GuestAuthToken>() {
        @Override
        public void success(Result<GuestAuthToken> result) {
            fail();
        }

        @Override
        public void failure(TwitterException error) {
            assertNotNull(error);
        }
    });
}
 
Example 11
Project: twitter-kit-android   File: OAuth2ServiceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testRequestGuestAuthToken_appAuthFailure() {

    service.api = new MockOAuth2Api() {
        @Override
        public Call<OAuth2Token> getAppAuthToken(@Header(OAuthConstants.HEADER_AUTHORIZATION) String auth,
                @Field(OAuthConstants.PARAM_GRANT_TYPE) String grantType) {
            return Calls.failure(new IOException());
        }
    };

    service.requestGuestAuthToken(new Callback<GuestAuthToken>() {
        @Override
        public void success(Result<GuestAuthToken> result) {
            fail();
        }

        @Override
        public void failure(TwitterException error) {
            assertNotNull(error);
        }
    });
}
 
Example 12
Project: twitter-kit-android   File: TwitterAuthClientTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testRequestEmail_withSuccess() {
    final User user = new UserBuilder().setEmail(TEST_EMAIL).build();
    final Call<User> call = Calls.response(user);
    setupMockAccountService(call);

    authClient.requestEmail(mock(TwitterSession.class), new Callback<String>() {
        @Override
        public void success(Result<String> result) {
            assertEquals(TEST_EMAIL, result.data);
        }

        @Override
        public void failure(TwitterException exception) {
            fail("Expected Callback#success to be called");
        }
    });
}
 
Example 13
Project: twitter-kit-android   File: TwitterAuthClientTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testRequestEmail_withFailure() {
    final IOException networkException = new IOException("Network failure");
    final Call<User> call = Calls.failure(networkException);
    setupMockAccountService(call);

    authClient.requestEmail(mock(TwitterSession.class), new Callback<String>() {
        @Override
        public void success(Result<String> result) {
            fail("Expected Callback#failure to be called");
        }

        @Override
        public void failure(TwitterException exception) {
            assertEquals(exception.getCause(), networkException);
        }
    });
}
 
Example 14
Project: twitter-kit-android   File: TwitterAuthClientTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testRequestEmail_scribesImpression() {
    final IOException networkException = new IOException("Network failure");
    final Call<User> call = Calls.failure(networkException);
    setupMockAccountService(call);

    final TwitterSession mockSession = mock(TwitterSession.class);
    when(mockSession.getId()).thenReturn(TestFixtures.USER_ID);
    authClient = new TwitterAuthClient(mockTwitterCore, mockAuthConfig, mockSessionManager,
            mockAuthState) {
        @Override
        protected DefaultScribeClient getScribeClient() {
            return mockScribeClient;
        }
    };

    authClient.requestEmail(mockSession, mock(Callback.class));

    verify(mockScribeClient).scribe(any(EventNamespace.class));
}
 
Example 15
Project: twitter-kit-android   File: TweetUploadServiceTest.java   Source Code and License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    context = RuntimeEnvironment.application;
    mockMediaService = mock(MediaService.class);
    mockStatusesService = mock(StatusesService.class);
    tweet =  new TweetBuilder().setId(123L).setText(EXPECTED_TWEET_TEXT).build();
    when(mockMediaService
            .upload(any(RequestBody.class), any(RequestBody.class), any(RequestBody.class)))
            .thenReturn(mock(Call.class));
    when(mockStatusesService.update(anyString(), isNull(Long.class), isNull(Boolean.class),
            isNull(Double.class), isNull(Double.class), isNull(String.class),
            isNull(Boolean.class), eq(true), isNull(String.class)))
            .thenReturn(Calls.response(tweet));

    mockTwitterApiClient = mock(TwitterApiClient.class);
    when(mockTwitterApiClient.getStatusesService()).thenReturn(mockStatusesService);
    when(mockTwitterApiClient.getMediaService()).thenReturn(mockMediaService);

    mockDependencyProvider = mock(TweetUploadService.DependencyProvider.class);
    when(mockDependencyProvider.getTwitterApiClient(any(TwitterSession.class)))
            .thenReturn(mockTwitterApiClient);

    service = spy(Robolectric.buildService(TweetUploadService.class).create().get());
    service.dependencyProvider = mockDependencyProvider;
}
 
Example 16
Project: twitter-kit-android   File: TweetUploadServiceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testUploadTweet_withNoMediaFailure() {
    when(mockStatusesService.update(anyString(), isNull(Long.class), isNull(Boolean.class),
            isNull(Double.class), isNull(Double.class), isNull(String.class),
            isNull(Boolean.class), eq(true), isNull(String.class)))
            .thenReturn(Calls.failure(new IOException("")));

    service.uploadTweet(mock(TwitterSession.class), EXPECTED_TWEET_TEXT, null);

    verify(mockStatusesService).update(eq(EXPECTED_TWEET_TEXT), isNull(Long.class),
            isNull(Boolean.class), isNull(Double.class), isNull(Double.class),
            isNull(String.class), isNull(Boolean.class), eq(true), isNull(String.class));
    verifyZeroInteractions(mockMediaService);
    verify(service).fail(any(TwitterException.class));
    verify(service).stopSelf();
}
 
Example 17
Project: android-retrofit-test-examples   File: MockFailedQODService.java   Source Code and License 6 votes vote down vote up
@Override
public Call<QuoteOfTheDayResponse> getQuoteOfTheDay() {
    za.co.riggaroo.retrofittestexample.pojo.Error error = new Error();
    error.setCode(404);
    error.setMessage("Quote Not Found");
    QuoteOfTheDayErrorResponse quoteOfTheDayErrorResponse = new QuoteOfTheDayErrorResponse();
    quoteOfTheDayErrorResponse.setError(error);

    ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
    String json = "";
    try {
        json = ow.writeValueAsString(quoteOfTheDayErrorResponse);
        Response response = Response.error(404, ResponseBody.create(MediaType.parse("application/json") ,json));
        return delegate.returning(Calls.response(response)).getQuoteOfTheDay();
       // return delegate.returningResponse(response).getQuoteOfTheDay();
    } catch (JsonProcessingException e) {
        Log.e(TAG, "JSON Processing exception:",e);
        return Calls.failure(e);
    }

}
 
Example 18
Project: filestack-java   File: TestImageTransform.java   Source Code and License 5 votes vote down vote up
@Test
public void testDebugHandle() throws Exception {
  Config config = new Config("apiKey");
  ImageTransform transform = new ImageTransform(config, "handle", false);

  Mockito
      .doReturn(Calls.response(new JsonObject()))
      .when(Networking.getCdnService())
      .transformDebug("", "handle");

  Assert.assertNotNull(transform.debug());
}
 
Example 19
Project: filestack-java   File: TestImageTransform.java   Source Code and License 5 votes vote down vote up
@Test
public void testDebugExternal() throws Exception {
  String url = "https://example.com/image.jpg";
  Config config = new Config("apiKey");
  ImageTransform transform = new ImageTransform(config, url, true);

  Mockito
      .doReturn(Calls.response(new JsonObject()))
      .when(Networking.getCdnService())
      .transformDebugExt("apiKey", "", url);

  Assert.assertNotNull(transform.debug());
}
 
Example 20
Project: filestack-java   File: TestImageTransform.java   Source Code and License 5 votes vote down vote up
@Test
public void testStoreHandle() throws Exception {
  Config config = new Config("apiKey");
  ImageTransform transform = new ImageTransform(config, "handle", false);
  String jsonString = "{'url': 'https://cdn.filestackcontent.com/handle'}";
  Gson gson = new Gson();
  StoreResponse storeResponse = gson.fromJson(jsonString, StoreResponse.class);

  Mockito
      .doReturn(Calls.response(storeResponse))
      .when(Networking.getCdnService())
      .transformStore("store", "handle");

  Assert.assertNotNull(transform.store());
}
 
Example 21
Project: filestack-java   File: TestClient.java   Source Code and License 5 votes vote down vote up
private static void setupCommitMock(UploadService mockUploadService) {
  MediaType mediaType = MediaType.parse("text/plain");
  final ResponseBody response = ResponseBody.create(mediaType, "");
  Mockito
      .doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
          return Calls.response(response);
        }
      })
      .when(mockUploadService)
      .commit(Mockito.<String, RequestBody>anyMap());
}
 
Example 22
Project: Mockery   File: RxRetrofitInterceptor.java   Source Code and License 5 votes vote down vote up
@Override public Observable onLegalMock(final Object mock, final Metadata<RxRetrofit> metadata) {
  checkReturnMethodTypeIsObservable(metadata);
  checkTypeMockIsNotObservableNeitherResponse(metadata, mock);

  NetworkBehavior networkBehavior = networkBehaviour(metadata);
  return callAdapter.adapt(metadata.getMethod(),
      networkBehavior, Calls.response(mock));
}
 
Example 23
Project: Mockery   File: RxRetrofitInterceptor.java   Source Code and License 5 votes vote down vote up
@Override public Observable onIllegalMock(final AssertionError assertionError, final Metadata<RxRetrofit> metadata) {
  checkReturnMethodTypeIsObservable(metadata);

  final String errorMessage = assertionError.getMessage() != null ? assertionError.getMessage() : "";
  final String adaptedErrorMessage = adaptErrorResponse(errorMessage, metadata);
  NetworkBehavior networkBehavior = networkBehaviour(metadata);

  final ResponseBody responseBody = ResponseBody
      .create(MediaType.parse("application/json"), adaptedErrorMessage);

  return callAdapter.adapt(metadata.getMethod(),
      networkBehavior, Calls.response(Response.error(404, responseBody)));
}
 
Example 24
Project: Mockery   File: Rx2RetrofitInterceptor.java   Source Code and License 5 votes vote down vote up
@Override public Object onLegalMock(final Object mock, final Metadata<Rx2Retrofit> metadata) {
  checkReturnMethodTypeIsSingleOrCompletable(metadata);
  checkTypeMockIsNotSingleNeitherResponse(metadata, mock);

  NetworkBehavior networkBehavior = networkBehaviour(metadata);
  return callAdapter.adapt(metadata.getMethod(),
      networkBehavior, Calls.response(mock));
}
 
Example 25
Project: Mockery   File: Rx2RetrofitInterceptor.java   Source Code and License 5 votes vote down vote up
@Override public Object onIllegalMock(final AssertionError assertionError, final Metadata<Rx2Retrofit> metadata) {
  checkReturnMethodTypeIsSingleOrCompletable(metadata);

  final String errorMessage = assertionError.getMessage() != null ? assertionError.getMessage() : "";
  final String adaptedErrorMessage = adaptErrorResponse(errorMessage, metadata);
  NetworkBehavior networkBehavior = networkBehaviour(metadata);

  final ResponseBody responseBody = ResponseBody
      .create(MediaType.parse("application/json"), adaptedErrorMessage);

  return callAdapter.adapt(metadata.getMethod(),
      networkBehavior, Calls.response(Response.error(404, responseBody)));
}
 
Example 26
Project: Mockery   File: RetrofitInterceptor.java   Source Code and License 5 votes vote down vote up
@Override public Call onLegalMock(Object mock, Metadata<Retrofit> metadata) {
  checkReturnMethodTypeIsCall(metadata);
  checkTypeMockIsNotCall(metadata, mock);

  NetworkBehavior networkBehavior = networkBehaviour(metadata);
  return callAdapter.adapt(metadata.getMethod(),
      networkBehavior, Calls.response(mock));
}
 
Example 27
Project: Mockery   File: RetrofitInterceptor.java   Source Code and License 5 votes vote down vote up
@Override public Call onIllegalMock(AssertionError assertionError, Metadata<Retrofit> metadata) {
  checkReturnMethodTypeIsCall(metadata);

  String errorMessage = assertionError.getMessage() != null ? assertionError.getMessage() : "";
  String safeErrorMessage = adaptErrorResponse(errorMessage, metadata);
  ResponseBody responseBody = ResponseBody
      .create(MediaType.parse("application/json"), safeErrorMessage);

  NetworkBehavior networkBehavior = networkBehaviour(metadata);
  return callAdapter.adapt(metadata.getMethod(),
      networkBehavior, Calls.response(Response.error(404, responseBody)));
}
 
Example 28
Project: Mockery   File: RetrofitInterceptorTest.java   Source Code and License 5 votes vote down vote up
@Test public void When_Call_Validate_With_Call_Error_Then_Throw_Assertion() {
  final ResponseBody responseBody = ResponseBody
      .create(MediaType.parse("application/json"), "BOOM!");

  exception.expect(AssertionError.class);

  retrofitInterceptor.validate(
      Calls.response(Response.error(404, responseBody)),
      metadataRetrofit());
}
 
Example 29
Project: segment-android   File: TransporterTest.java   Source Code and License 5 votes vote down vote up
@Test public void invokesCallback() throws ExecutionException, InterruptedException {
  Message message = new TrackMessage.Builder().userId("userId").event("event").build();

  transporter.enqueue(message).get();
  verify(callback).success(Callback.Event.PERSIST, message);

  Call<Void> call = Calls.response(Response.success((Void) null));
  when(trackingAPI.batch(any(Batch.class))).thenReturn(call);
  transporter.flush().get();
  verify(callback).success(Callback.Event.UPLOAD, message);
}
 
Example 30
Project: segment-android   File: TransporterTest.java   Source Code and License 5 votes vote down vote up
@Test public void ignoresNullCallback() throws ExecutionException, InterruptedException {
  transporter = new Transporter(queue, trackingAPI, null);

  Message message = new TrackMessage.Builder().userId("userId").event("event").build();

  transporter.enqueue(message).get();

  Call<Void> call = Calls.response(Response.success((Void) null));
  when(trackingAPI.batch(any(Batch.class))).thenReturn(call);
  transporter.flush().get();
}
 
Example 31
Project: segment-android   File: TransporterTest.java   Source Code and License 5 votes vote down vote up
@Test public void trimsBatches() throws Exception {
  for (int i = 0; i < 40; i++) {
    queue.add(new TrackMessage.Builder().userId("userId").event("event").build());
  }

  Call<Void> call = Calls.response(Response.success((Void) null));
  when(trackingAPI.batch(any(Batch.class))).thenReturn(call);

  transporter.flush().get();

  ArgumentCaptor<Batch> batchArgumentCaptor = ArgumentCaptor.forClass(Batch.class);
  verify(trackingAPI).batch(batchArgumentCaptor.capture());

  assertThat(batchArgumentCaptor.getValue().batch()).hasSize(33);
}
 
Example 32
Project: quill   File: MockGhostApiService.java   Source Code and License 5 votes vote down vote up
@Override
public Observable<AuthToken> getAuthToken(@Body AuthReqBody credentials) {
    if ((mUseGhostAuth && credentials.authorizationCode.equals("auth-code"))
            || (!mUseGhostAuth && credentials.password.equals("password"))) {
        AuthToken token = new AuthToken();
        token.setAccessToken("access-token");
        token.setRefreshToken("refresh-token");
        token.setCreatedAt(System.currentTimeMillis());
        token.setExpiresIn(60 * 1000);
        return mDelegate
                .returningResponse(token)
                .getAuthToken(credentials);
    } else {
        // wrong Ghost auth code or password
        // Mock Retrofit doesn't set the correct request URL, it sets just http://localhost
        String tokenUrl = "http://localhost/authentication/token/";
        ResponseBody body = ResponseBody.create(MediaType.parse("application/json"),
                "{\"errors\":[{\"message\":\"Your password is incorrect.\",\"context\":\"Your password is incorrect.\",\"errorType\":\"ValidationError\"}]}");
        final okhttp3.Response rawResponse = new okhttp3.Response.Builder()
                .protocol(Protocol.HTTP_1_1)
                .request(new Request.Builder().url(tokenUrl).build())
                .code(HttpURLConnection.HTTP_UNAUTHORIZED).message("Unauthorized")
                .body(body)
                .build();
        final Response<Object> res = Response.error(body, rawResponse);
        return mDelegate
                .returning(Calls.response(res))
                .getAuthToken(credentials);
    }
}
 
Example 33
Project: twitter-kit-android   File: ScribeFilesSenderTest.java   Source Code and License 5 votes vote down vote up
private Call<ResponseBody> errorResponse(int statusCode) {
    final ResponseBody body = ResponseBody.create(MediaType.parse("application/json"), "");
    return Calls.response(Response.<ResponseBody>error(statusCode, body));
}
 
Example 34
Project: twitter-kit-android   File: TwitterSessionVerifierTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testVerifySession_catchesRetrofitExceptionsAndFinishesVerification() {
    doReturn(Calls.failure(new IOException()))
            .when(mockAccountService).verifyCredentials(true, false, false);

    verifier.verifySession(session);

    verify(mockAccountService).verifyCredentials(true, false, false);
    // success, we caught the exception
}
 
Example 35
Project: edx-app-android   File: UserProfileInteractorTest.java   Source Code and License 5 votes vote down vote up
@Test
public void whenProfileObserved_withGetAccountError_emitsError() {
    final IOException exception = new IOException();
    when(userService.getAccount(ProfileValues.USERNAME)).thenReturn(Calls.<Account>failure(exception));
    createAndObserveInteractor();
    verify(profileObserver).onError(exception);
}
 
Example 36
Project: edx-app-android   File: UserProfileInteractorTest.java   Source Code and License 5 votes vote down vote up
@NonNull
private Account configureBareMockAccount() {
    final Account account = mock(Account.class);
    when(account.getUsername()).thenReturn(ProfileValues.USERNAME);
    when(account.getProfileImage()).thenReturn(mock(ProfileImage.class));
    when(userService.getAccount(ProfileValues.USERNAME)).thenReturn(Calls.response(account));
    return account;
}
 
Example 37
Project: filestack-java   File: Helpers.java   Source Code and License 4 votes vote down vote up
/**
 * Helper method for creating raw ({@link ResponseBody}) {@link Call} objects.
 */
public static Call<ResponseBody> createRawCall(String contentType, String body) {
  MediaType mediaType = MediaType.parse(contentType);
  ResponseBody responseBody = ResponseBody.create(mediaType, body);
  return Calls.response(responseBody);
}
 
Example 38
Project: Mockery   File: RetrofitInterceptorTest.java   Source Code and License 4 votes vote down vote up
@Test public void When_Mock_Seed_Is_Type_Call_Then_Get_Exception() {
  exception.expect(RuntimeException.class);
  retrofitInterceptor.onLegalMock(Calls.response(new Mock()), metadataRetrofit());
}
 
Example 39
Project: Mockery   File: RetrofitInterceptorTest.java   Source Code and License 4 votes vote down vote up
@Test public void When_Call_Validate_With_Call_Then_Do_Not_Throw_Assertion() {
  retrofitInterceptor.validate(Calls.response(new Mock()), metadataRetrofit());
}
 
Example 40
Project: Mockery   File: RetrofitInterceptorTest.java   Source Code and License 4 votes vote down vote up
@Test public void When_Call_Adapt_Response_With_Call_Then_Unwrap_Its_Value() {
  Mock mock = (Mock) retrofitInterceptor
      .adaptResponse(Calls.response(new Mock()), metadataRetrofit());
  assertNotNull(mock);
}
 
Example 41
Project: twitter-kit-android   File: ScribeFilesSenderTest.java   Source Code and License 4 votes vote down vote up
private Call<ResponseBody> successResponse() {
    final ResponseBody body = ResponseBody.create(MediaType.parse("application/json"), "");
    return Calls.response(body);
}
 
Example 42
Project: twitter-kit-android   File: OAuth1aServiceTest.java   Source Code and License 4 votes vote down vote up
@Override
public Call<ResponseBody> getTempToken(@Header(OAuthConstants.HEADER_AUTHORIZATION) String auth) {
    final ResponseBody responseBody = ResponseBody.create(MediaType.parse("application/json"), "");
    return Calls.response(Response.success(responseBody));
}
 
Example 43
Project: twitter-kit-android   File: OAuth1aServiceTest.java   Source Code and License 4 votes vote down vote up
@Override
public Call<ResponseBody> getAccessToken(@Header(OAuthConstants.HEADER_AUTHORIZATION) String auth,
        @Query(OAuthConstants.PARAM_VERIFIER) String verifier) {
    final ResponseBody responseBody = ResponseBody.create(MediaType.parse("application/json"), "");
    return Calls.response(Response.success(responseBody));
}
 
Example 44
Project: twitter-kit-android   File: OAuth2ServiceTest.java   Source Code and License 4 votes vote down vote up
@Override
public Call<GuestTokenResponse> getGuestToken(@Header(OAuthConstants.HEADER_AUTHORIZATION) String auth) {
    return Calls.response(Response.success(GUEST_RESPONSE));
}
 
Example 45
Project: twitter-kit-android   File: OAuth2ServiceTest.java   Source Code and License 4 votes vote down vote up
@Override
public Call<OAuth2Token> getAppAuthToken(@Header(OAuthConstants.HEADER_AUTHORIZATION) String auth,
                                         @Field(OAuthConstants.PARAM_GRANT_TYPE) String grantType) {
    return Calls.response(Response.success(APP_TOKEN));
}
 
Example 46
Project: edx-app-android   File: UserProfileInteractorTest.java   Source Code and License 4 votes vote down vote up
@Test
public void getUsername_returnsUsernamePassedInConstructor() {
    when(userService.getAccount(ProfileValues.USERNAME)).thenReturn(Calls.<Account>failure(new IOException()));
    createAndObserveInteractor();
    assertThat(interactor.getUsername(), is(ProfileValues.USERNAME));
}
 
Example 47
Project: pagerduty-incidents   File: RecordingEventService.java   Source Code and License 4 votes vote down vote up
@Override public Call<NotifyResult> notify(Event event) {
  events.add(event);
  return Calls.response((NotifyResult) null);
}