retrofit2.mock.Calls Java Examples

The following examples show how to use retrofit2.mock.Calls. 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: TheResolverWithMockApiShould.java    From android-sdk with MIT License 7 votes vote down vote up
@Test
public void test_enter_exit_action() throws Exception {
    ResolveResponse resolveResponse = gson
            .fromJson(Utils.getRawResourceAsString(com.sensorberg.sdk.test.R.raw.resolve_response_enter_exit_action, InstrumentationRegistry
                    .getContext()), ResolveResponse.class);
    Mockito.when(mockRetrofitApiService.getBeacon(Mockito.anyString(), Mockito.anyString(), Matchers.<TreeMap<String, String>>any()))
            .thenReturn(Calls.response(resolveResponse));

    ResolverListener testListener = new ResolverListener() {
        @Override
        public void onResolutionFailed(Throwable cause, ScanEvent scanEvent) {
            Assert.fail(cause.getMessage());
        }

        @Override
        public void onResolutionsFinished(List<BeaconEvent> events) {
            Assertions.assertThat(events).hasSize(1);
        }
    };

    tested.setListener(testListener);
    tested.resolve(TestConstants.RESOLVABLE_ENTRY_EVENT_WITH_ID_3);
}
 
Example #2
Source File: TweetUploadServiceTest.java    From twitter-kit-android with Apache License 2.0 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 #3
Source File: TwitterAuthClientTest.java    From twitter-kit-android with Apache License 2.0 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 #4
Source File: OAuth2ServiceTest.java    From twitter-kit-android with Apache License 2.0 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 #5
Source File: OAuth2ServiceTest.java    From twitter-kit-android with Apache License 2.0 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 #6
Source File: CallbackWithRetryShould.java    From android-sdk with MIT License 6 votes vote down vote up
@Test
public void callback_with_retry_should_retry_3_times() throws Exception {
    Call<SettingsResponse> exceptionResponse = Calls.failure(new UnsupportedEncodingException());
    Mockito.when(mockRetrofitApiService.getSettings()).thenReturn(exceptionResponse);
    Call<SettingsResponse> call = mockRetrofitApiService.getSettings();
    Callback<SettingsResponse> mockedOriginalCallback = Mockito.spy(Callback.class);
    CallbackWithRetry<SettingsResponse> retryCallback = new CallbackWithRetry<>(mockedOriginalCallback);
    CallbackWithRetry<SettingsResponse> spiedRetryCallback = Mockito.spy(retryCallback);

    call.enqueue(spiedRetryCallback);

    Mockito.verify(mockedOriginalCallback, times(1)).onFailure(any(Call.class), any(Exception.class));
    Mockito.verify(mockedOriginalCallback, times(0)).onResponse(any(Call.class), any(Response.class));
    Mockito.verify(spiedRetryCallback, times(3)).onFailure(any(Call.class), any(Exception.class));
    Mockito.verify(spiedRetryCallback, times(0)).onResponse(any(Call.class), any(Response.class));
}
 
Example #7
Source File: TwitterAuthClientTest.java    From twitter-kit-android with Apache License 2.0 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 #8
Source File: TransportShould.java    From android-sdk with MIT License 6 votes vote down vote up
@Test
public void test_failures() throws Exception {
    Call<SettingsResponse> exceptionResponse = Calls.failure(new UnsupportedEncodingException());
    Mockito.when(mockRetrofitApiService.getSettings()).thenReturn(exceptionResponse);

    tested.loadSettings(new TransportSettingsCallback() {
        @Override
        public void nothingChanged() {
            Assert.fail();
        }

        @Override
        public void onFailure(Exception e) {
            Assert.assertNotNull(e);
        }

        @Override
        public void onSettingsFound(SettingsResponse settings) {
            Assert.fail();
        }
    });
}
 
Example #9
Source File: TransportShould.java    From android-sdk with MIT License 6 votes vote down vote up
@Test
    public void test_a_beacon_request() throws Exception {
        ResolveResponse response = gson.fromJson(
                Utils.getRawResourceAsString(com.sensorberg.sdk.test.R.raw.resolve_response_005, InstrumentationRegistry.getContext()),
                ResolveResponse.class);
        Mockito.when(mockRetrofitApiService.getBeacon(anyString(), anyString(), Matchers.<TreeMap<String, String>>any())).thenReturn(Calls.response(response));

        Assertions.assertThat(response).isNotNull();
        tested.getBeacon(TestConstants.BEACON_SCAN_ENTRY_EVENT(clock.now()), null, new BeaconResponseHandler() {
            @Override
            public void onSuccess(List<BeaconEvent> foundBeaconEvents) {
                Assertions
                        .assertThat(foundBeaconEvents)
//                        .overridingErrorMessage("There should be 1 action to the Beacon %s at %s there were %d",
//                                TestConstants.BEACON_SCAN_ENTRY_EVENT(clock.now()).getBeaconId().toTraditionalString(),
//                                foundBeaconEvents.size())
                        .isNotNull()
                        .hasSize(1);
            }

            @Override
            public void onFailure(Throwable cause) {
                Assert.fail("there was a failure with this request");
            }
        });
    }
 
Example #10
Source File: TransportShould.java    From android-sdk with MIT License 6 votes vote down vote up
@Test
public void test_a_settings_request() {
    Mockito.when(mockRetrofitApiService.getSettings()).thenReturn(Calls.response(new SettingsResponse(0, new Settings())));

    tested.loadSettings(new TransportSettingsCallback() {
        @Override
        public void nothingChanged() {
            Assert.fail("there should be changes to no settings");
        }

        @Override
        public void onFailure(Exception e) {
            Assert.fail();
        }

        @Override
        public void onSettingsFound(SettingsResponse settings) {
            Assertions.assertThat(settings).isNotNull();
        }
    });
}
 
Example #11
Source File: TweetUploadServiceTest.java    From twitter-kit-android with Apache License 2.0 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 #12
Source File: TheResolverWithMockApiShould.java    From android-sdk with MIT License 6 votes vote down vote up
@Test
public void test_resolve_in_app_function() throws Exception {
    ResolveResponse resolveResponse = gson
            .fromJson(Utils.getRawResourceAsString(com.sensorberg.sdk.test.R.raw.resolve_response_inapp_action, InstrumentationRegistry
                    .getContext()), ResolveResponse.class);
    Mockito.when(mockRetrofitApiService.getBeacon(Mockito.anyString(), Mockito.anyString(), Matchers.<TreeMap<String, String>>any()))
            .thenReturn(Calls.response(resolveResponse));

    ResolverListener mockListener = new ResolverListener() {
        @Override
        public void onResolutionFailed(Throwable cause, ScanEvent scanEvent) {
            Assert.fail(cause.getMessage());
        }

        @Override
        public void onResolutionsFinished(List<BeaconEvent> events) {
            Assertions.assertThat(events).hasSize(3);
        }

    };

    tested.setListener(mockListener);
    tested.resolve(TestConstants.RESOLVABLE_ENTRY_EVENT_WITH_INAPP_ACTIONS);
}
 
Example #13
Source File: MockGhostApiService.java    From quill with MIT 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 #14
Source File: MockFailedQODService.java    From android-retrofit-test-examples with MIT 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 #15
Source File: TransportShould.java    From android-sdk with MIT License 5 votes vote down vote up
@Test
public void test_should_forward_the_layout_upload_interval_to_the_settings() throws Exception {
    BeaconHistoryUploadIntervalListener mockListener = mock(BeaconHistoryUploadIntervalListener.class);
    tested.setBeaconHistoryUploadIntervalListener(mockListener);

    ResolveResponse resolveResponse = new ResolveResponse.Builder().withReportTrigger(1337).build();
    Mockito.when(mockRetrofitApiService.getBeacon(anyString(), anyString(), Matchers.<TreeMap<String, String>>any()))
            .thenReturn(Calls.response(resolveResponse));

    tested.getBeacon(TestConstants.BEACON_SCAN_ENTRY_EVENT(clock.now()), null, BeaconResponseHandler.NONE);
    Mockito.verify(mockListener).historyUploadIntervalChanged(1337L * 1000);
}
 
Example #16
Source File: TheInternalBootstrapperIntegration.java    From android-sdk with MIT License 5 votes vote down vote up
@Test
    public void test_an_instant_action_workflow() throws Exception {
        //enqueue the layout with a beacon for report immediately
        Mockito.when(mockRetrofitApiService.getBeacon( Mockito.anyString(), Mockito.anyString(), Matchers.<TreeMap<String, String>>any()))
                .thenReturn(Calls.response(RESOLVE_RESPONSE_WITH_REPORT_IMMEDIATELY));

        //enqueue the reporting result
        Mockito.when(mockRetrofitApiService.publishHistory(Mockito.any(HistoryBody.class)))
                .thenReturn(Calls.response(PUBLISH_HISTORY_RESPONSE));

        System.out.println("TheInternalBootstrapperIntegration start test_an_instant_action_workflow");

        //simulate the entry
        spiedInternalApplicationBootstrapper.onScanEventDetected(new ScanEvent.Builder()
                .withBeaconId(TestConstants.ANY_BEACON_ID)
                .withEntry(true)
                .build());

        //we should have exactly one notification
        Mockito.verify(spiedTransportWithMockService, Mockito.timeout(5000).times(1))
                .getBeacon(Mockito.any(ScanEvent.class), Matchers.<TreeMap<String, String>>any(), Mockito.any(BeaconResponseHandler.class));

        //TODO this does get called in real code and during debugging, but Mockito says it doesn't
//        Mockito.verify(spiedTransportWithMockService, Mockito.timeout(5000).times(1))
//                .publishHistory(Mockito.anyList(), Mockito.anyList(), Mockito.any(TransportHistoryCallback.class));
//        Mockito.verify(spiedInternalApplicationBootstrapper, Mockito.timeout(5000).times(1))
//                .presentBeaconEvent(Mockito.any(BeaconEvent.class));

        System.out.println("TheInternalBootstrapperIntegration end");
    }
 
Example #17
Source File: UserProfileInteractorTest.java    From edx-app-android with Apache License 2.0 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 #18
Source File: TheInternalBootstrapperIntegration.java    From android-sdk with MIT License 5 votes vote down vote up
@Test
    public void test_precaching() {
        try {
            ResolveResponse updateLayoutResponse = gson
                    .fromJson(Utils.getRawResourceAsString(com.sensorberg.sdk.test.R.raw.response_resolve_precaching,
                            InstrumentationRegistry.getContext()), ResolveResponse.class);
            Mockito.when(mockRetrofitApiService.updateBeaconLayout(Matchers.<TreeMap<String, String>>any())).thenReturn(Calls.response(updateLayoutResponse));

            ResolveResponse getBeaconResponse = gson.fromJson(Utils.getRawResourceAsString(com.sensorberg.sdk.test.R.raw.response_resolve_precaching,
                    InstrumentationRegistry.getContext()), ResolveResponse.class);
            Mockito.when(mockRetrofitApiService.getBeacon(Mockito.anyString(), Mockito.anyString(), Matchers.<TreeMap<String, String>>any()))
                    .thenReturn(Calls.response(getBeaconResponse));
        } catch (Exception e) {
            Assertions.fail(e.toString());
        }

        System.out.println("TheInternalBootstrapperIntegration start test_precaching");
        spiedInternalApplicationBootstrapper.updateBeaconLayout();

        //simulate the entry
        spiedInternalApplicationBootstrapper.onScanEventDetected(TestConstants.BEACON_SCAN_ENTRY_EVENT(0));

        Mockito.verify(spiedTransportWithMockService, Mockito.timeout(5000).times(1))
                .getBeacon(Mockito.any(ScanEvent.class), Matchers.<TreeMap<String, String>>any(), Mockito.any(BeaconResponseHandler.class));
        Mockito.verify(spiedTransportWithMockService, Mockito.timeout(5000).times(1))
                .updateBeaconLayout(Matchers.<TreeMap<String, String>>any());

        //TODO this does get called in real code and during debugging, but Mockito says it doesn't
//        Mockito.verify(spiedInternalApplicationBootstrapper, Mockito.timeout(5000).times(1))
//                .presentBeaconEvent(Mockito.any(BeaconEvent.class));
    }
 
Example #19
Source File: RxRetrofitInterceptor.java    From Mockery with Apache License 2.0 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 #20
Source File: TransportShould.java    From android-sdk with MIT License 5 votes vote down vote up
@Test
public void transport_settings_call_should_call_enqueue_with_retry() throws Exception {
    Mockito.when(mockRetrofitApiService.getSettings()).thenReturn(Calls.response(new SettingsResponse(0, new Settings())));
    TransportSettingsCallback transportSettingsCallback = mock(TransportSettingsCallback.class);
    RetrofitApiTransport spiedTransport = (RetrofitApiTransport) Mockito.spy(tested);

    spiedTransport.loadSettings(transportSettingsCallback);
    Mockito.verify(spiedTransport, times(1)).enqueueWithRetry(any(Call.class), any(retrofit2.Callback.class));
}
 
Example #21
Source File: TheSettingsShould.java    From android-sdk with MIT License 5 votes vote down vote up
@Test
public void test_parsing_settings_from_network_response() throws Exception {
    SettingsResponse settingsResponse = gson.fromJson(
            Utils.getRawResourceAsString(com.sensorberg.sdk.test.R.raw.response_settings_newdefaults, InstrumentationRegistry
                    .getContext()), SettingsResponse.class);
    Mockito.when(mockRetrofitApiService.getSettings()).thenReturn(Calls.response(settingsResponse));

    Assertions.assertThat(settingsResponse).isNotNull();
    Assertions.assertThat(settingsResponse.getRevision()).isEqualTo(1L);
    Assertions.assertThat(settingsResponse.getSettings().getBackgroundWaitTime()).isEqualTo(100000L);
    Assertions.assertThat(settingsResponse.getSettings().getBeaconReportLevel()).isEqualTo(1);
    Assertions.assertThat(settingsResponse.getSettings().getScannerMinRssi()).isEqualTo(-10);
    Assertions.assertThat(settingsResponse.getSettings().getScannerMaxDistance()).isEqualTo(5);
}
 
Example #22
Source File: TheSettingsShould.java    From android-sdk with MIT License 5 votes vote down vote up
@Test
public void test_fetch_values_from_the_network() throws Exception {
    SettingsResponse settingsResponse = gson.fromJson(
            Utils.getRawResourceAsString(com.sensorberg.sdk.test.R.raw.response_settings_newdefaults, InstrumentationRegistry.getContext()),
            SettingsResponse.class);
    Mockito.when(mockRetrofitApiService.getSettings()).thenReturn(Calls.response(settingsResponse));

    tested.updateSettingsFromNetwork();

    Assertions.assertThat(tested.getBackgroundWaitTime()).isNotEqualTo(DefaultSettings.DEFAULT_BACKGROUND_WAIT_TIME);
    Assertions.assertThat(tested.getSettingsRevision()).isNotNull();
    Assertions.assertThat(tested.getSettingsRevision()).isEqualTo(1L);
}
 
Example #23
Source File: TheResolverWithMockApiShould.java    From android-sdk with MIT License 5 votes vote down vote up
@Test
public void test_beacon_with_delay() throws Exception {
    ResolveResponse resolveResponse = gson
            .fromJson(Utils.getRawResourceAsString(com.sensorberg.sdk.test.R.raw.resolve_response_delayed_action, InstrumentationRegistry
                    .getContext()), ResolveResponse.class);
    Mockito.when(mockRetrofitApiService.getBeacon(Mockito.anyString(), Mockito.anyString(), Matchers.<TreeMap<String, String>>any()))
            .thenReturn(Calls.response(resolveResponse));

    ResolverListener mockListener = mock(ResolverListener.class);
    tested.setListener(mockListener);

    tested.resolve(TestConstants.RESOLVABLE_ENTRY_EVENT_WITH_ID_3);

    verify(mockListener).onResolutionsFinished(argThat(new BaseMatcher<List<BeaconEvent>>() {
        public long delay;

        @Override
        public boolean matches(Object o) {
            List<BeaconEvent> list = (List<BeaconEvent>) o;
            delay = list.get(0).getAction().getDelayTime();
            return delay == 120000;
        }

        @Override
        public void describeTo(Description description) {
            description.appendText(String.format("Delaytime was %d and not %d as expected", delay, 120000));
        }
    }));
}
 
Example #24
Source File: TheBeaconActionHistoryPublisherIntegrationShould.java    From android-sdk with MIT License 5 votes vote down vote up
@Test
public void test_should_send_history_to_the_server() throws Exception {
    Mockito.when(mockRetrofitApiService.publishHistory(Mockito.any(HistoryBody.class)))
            .thenReturn(Calls.response(PUBLISH_HISTORY_RESPONSE));

    tested.onScanEventDetected(TestConstants.BEACON_SCAN_ENTRY_EVENT(100));
    tested.publishHistory();

    verify(mockRetrofitApiService, times(1)).publishHistory(Mockito.any(HistoryBody.class));
}
 
Example #25
Source File: TheBeaconActionHistoryPublisherIntegrationShould.java    From android-sdk with MIT License 5 votes vote down vote up
@Test
public void test_should_send_no_history_to_the_server_when_nothing_happend() throws Exception {
    Mockito.when(mockRetrofitApiService.publishHistory(Mockito.any(HistoryBody.class)))
            .thenReturn(Calls.response(PUBLISH_HISTORY_RESPONSE));

    tested.publishHistory();

    verify(mockRetrofitApiService, never()).publishHistory(Mockito.any(HistoryBody.class));
}
 
Example #26
Source File: UserProfileInteractorTest.java    From edx-app-android with Apache License 2.0 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 #27
Source File: MockGhostApiService.java    From quill with MIT 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 #28
Source File: TwitterSessionVerifierTest.java    From twitter-kit-android with Apache License 2.0 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 #29
Source File: RxRetrofitInterceptor.java    From Mockery with Apache License 2.0 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 #30
Source File: Rx2RetrofitInterceptor.java    From Mockery with Apache License 2.0 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));
}