Java Code Examples for io.reactivex.observers.TestObserver#assertValueCount()

The following examples show how to use io.reactivex.observers.TestObserver#assertValueCount() . 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: Rx2RetrofitInterceptorTest.java    From Mockery with Apache License 2.0 6 votes vote down vote up
@Test
public void When_Call_OnIllegalMock_If_Method_Return_Type_Is_Single_Response_Then_Get_Response_Body_Null()
    throws NoSuchMethodException, IOException {
  Method method = Providers.class.getDeclaredMethod("singleResponseMock");
  Rx2Retrofit annotation = PlaceholderRetrofitAnnotation.class.getAnnotation(Rx2Retrofit.class);
  Metadata<Rx2Retrofit> metadata = new Metadata(Providers.class,
      method, null, annotation, method.getGenericReturnType());

  Single single = (Single) rx2RetrofitInterceptor
      .onIllegalMock(new AssertionError("BOOM!"), metadata);
  TestObserver<Response<Mock>> subscriber = single.test();
  subscriber.awaitTerminalEvent();
  subscriber.assertNoErrors();
  subscriber.assertValueCount(1);

  Response<Mock> response = subscriber.values().get(0);
  assertNull(response.body());
  assertFalse(response.isSuccessful());
  assertThat(response.errorBody().string(), is("BOOM!"));
}
 
Example 2
Source File: RxDatabaseReferenceTest.java    From rxfirebase with Apache License 2.0 6 votes vote down vote up
@Test
public void testDataChanges_DataReference() {
    TestObserver<DataSnapshot> sub = TestObserver.create();

    RxDatabaseReference.changes(mockDatabaseReference)
            .subscribe(sub);

    verifyDataReferenceAddValueEventListener();
    callValueEventOnDataChange("Foo");

    sub.assertNotComplete();
    sub.assertValueCount(1);

    sub.dispose();

    callValueEventOnDataChange("Foo");

    // Ensure no more values are emitted after unsubscribe
    sub.assertValueCount(1);
}
 
Example 3
Source File: RibActivityTest.java    From RIBs with Apache License 2.0 6 votes vote down vote up
@Test
public void ribActivity_onSaveInstanceStateAndCallbackFlagEnabled_shouldEmitToCallbacks() {
  ActivityController<EmptyActivity> activityController = buildActivity(EmptyActivity.class);
  RibActivity activity = activityController.setup().get();
  TestObserver<ActivityCallbackEvent.SaveInstanceState> testSub = new TestObserver<>();
  activity.callbacks(ActivityCallbackEvent.SaveInstanceState.class).subscribe(testSub);

  android.os.Bundle state = new android.os.Bundle();
  state.putString("hello", "seattle");
  activity.onSaveInstanceState(state);

  testSub.assertValueCount(1);
  ActivityCallbackEvent.SaveInstanceState receivedEvent = testSub.values().get(0);
  assertThat(receivedEvent.getType()).isEqualTo(ActivityCallbackEvent.Type.SAVE_INSTANCE_STATE);
  assertThat(receivedEvent.getOutState()).isNotNull();
  assertThat(receivedEvent.getOutState().getString("hello")).isEqualTo("seattle");
}
 
Example 4
Source File: RxFirebaseUserTest.java    From rxfirebase with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnlink() {
    mockSuccessfulAuthResult();
    when(mockFirebaseUser.unlink("provider"))
            .thenReturn(mockAuthTaskResult);

    TestObserver<FirebaseUser> obs = TestObserver.create();

    RxFirebaseUser.unlink(mockFirebaseUser, "provider")
            .subscribe(obs);

    callOnComplete(mockAuthTaskResult);
    obs.dispose();

    // Ensure no more values are emitted after unsubscribe
    callOnComplete(mockAuthTaskResult);

    obs.assertComplete();
    obs.assertValueCount(1);
}
 
Example 5
Source File: RxFirebaseAuthTest.java    From rxfirebase with Apache License 2.0 6 votes vote down vote up
@Test
public void testFetchProvidersForEmail() {
    when(mockFirebaseAuth.fetchProvidersForEmail("[email protected]"))
            .thenReturn(mockFetchProvidersTask);

    mockSuccessfulFetchProvidersResult();

    when(mockFirebaseAuth.fetchProvidersForEmail("[email protected]"))
            .thenReturn(mockFetchProvidersTask);

    TestObserver<List<String>> obs = TestObserver.create();

    RxFirebaseAuth
            .fetchProvidersForEmail(mockFirebaseAuth, "[email protected]")
            .subscribe(obs);

    callOnComplete(mockFetchProvidersTask);
    obs.dispose();

    // Ensure no more values are emitted after unsubscribe
    callOnComplete(mockFetchProvidersTask);

    obs.assertComplete();
    obs.assertValueCount(1);
}
 
Example 6
Source File: RxPaperBookTest.java    From RxPaper2 with MIT License 6 votes vote down vote up
@Test
public void testExists() throws Exception {
    RxPaperBook book = RxPaperBook.with("EXISTS", Schedulers.trampoline());
    final String key = "hello";
    book.write(key, ComplexObject.random()).subscribe();
    final TestObserver<Boolean> foundSubscriber = book.exists(key).test();
    foundSubscriber.awaitTerminalEvent();
    foundSubscriber.assertNoErrors();
    foundSubscriber.assertValueCount(1);
    foundSubscriber.assertValues(true);
    // notFoundSubscriber
    String noKey = ":(";
    final TestObserver<Boolean> notFoundSubscriber = book.exists(noKey).test();
    notFoundSubscriber.awaitTerminalEvent();
    notFoundSubscriber.assertComplete();
    notFoundSubscriber.assertValueCount(1);
    notFoundSubscriber.assertValues(false);
}
 
Example 7
Source File: ExceptionHandlingIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenSubscriberAndError_whenHandleOnErrorResumeItem_thenResumed() {
    TestObserver<String> testObserver = new TestObserver<>();

    Observable
      .<String>error(UNKNOWN_ERROR)
      .onErrorReturnItem("singleValue")
      .subscribe(testObserver);

    testObserver.assertNoErrors();
    testObserver.assertComplete();
    testObserver.assertValueCount(1);
    testObserver.assertValue("singleValue");
}
 
Example 8
Source File: ExceptionHandlingIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenSubscriberAndError_whenHandleOnErrorResume_thenResumed() {
    TestObserver<String> testObserver = new TestObserver<>();

    Observable
      .<String>error(UNKNOWN_ERROR)
      .onErrorResumeNext(Observable.just("one", "two"))
      .subscribe(testObserver);

    testObserver.assertNoErrors();
    testObserver.assertComplete();
    testObserver.assertValueCount(2);
    testObserver.assertValues("one", "two");
}
 
Example 9
Source File: RxPaperBookTest.java    From RxPaper2 with MIT License 5 votes vote down vote up
@Test
public void testGetPathForKey() throws Exception {
    RxPaperBook book = RxPaperBook.with("PATH", Schedulers.trampoline());
    final String key = "hello";
    final TestObserver<String> emptyBookSubscriber = book.getPath(key).test();
    emptyBookSubscriber.awaitTerminalEvent();
    emptyBookSubscriber.assertNoErrors();
    emptyBookSubscriber.assertValueCount(1);
    book.write(key, ComplexObject.random()).subscribe();
    final TestObserver<String> foundSubscriber = book.getPath(key).test();
    foundSubscriber.awaitTerminalEvent();
    foundSubscriber.assertNoErrors();
    foundSubscriber.assertValueCount(1);
}
 
Example 10
Source File: UserServiceTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldLoadUserByUsernameAndDomain() {
    when(userRepository.findByUsernameAndDomain(DOMAIN, "my-user")).thenReturn(Maybe.just(new User()));
    TestObserver testObserver = userService.findByDomainAndUsername(DOMAIN, "my-user").test();

    testObserver.awaitTerminalEvent();
    testObserver.assertComplete();
    testObserver.assertNoErrors();
    testObserver.assertValueCount(1);
}
 
Example 11
Source File: ExceptionHandlingIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenSubscriberAndError_whenHandleOnErrorReturn_thenResumed() {
    TestObserver<String> testObserver = new TestObserver<>();

    Observable
      .<String>error(UNKNOWN_ERROR)
      .onErrorReturn(Throwable::getMessage)
      .subscribe(testObserver);

    testObserver.assertNoErrors();
    testObserver.assertComplete();
    testObserver.assertValueCount(1);
    testObserver.assertValue("unknown error");
}
 
Example 12
Source File: RoleServiceTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldFindById() {
    when(roleRepository.findById("my-role")).thenReturn(Maybe.just(new Role()));
    TestObserver testObserver = roleService.findById("my-role").test();

    testObserver.awaitTerminalEvent();
    testObserver.assertComplete();
    testObserver.assertNoErrors();
    testObserver.assertValueCount(1);
}
 
Example 13
Source File: EmailTemplateServiceTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldFindAll() {
    when(emailRepository.findAll(ReferenceType.DOMAIN, DOMAIN)).thenReturn(Single.just(Collections.singletonList(new Email())));
    TestObserver testObserver = emailTemplateService.findAll(ReferenceType.DOMAIN, DOMAIN).test();

    testObserver.awaitTerminalEvent();
    testObserver.assertComplete();
    testObserver.assertNoErrors();
    testObserver.assertValueCount(1);
}
 
Example 14
Source File: StepTest.java    From RIBs with Apache License 2.0 5 votes vote down vote up
@Test
public void asObservable_withInactiveLifecycle_shouldWaitForActiveLifecycleBeforeEmitting() {
  Object returnValue = new Object();
  TestObserver<Optional<Step.Data<Object, ActionableItem>>> testSubscriber = new TestObserver<>();

  step.asObservable().subscribe(testSubscriber);

  testSubscriber.assertNoValues();
  testSubscriber.assertNoErrors();
  testSubscriber.assertNotComplete();

  returnValueSubject.onNext(
      Optional.of(
          new Step.Data<Object, ActionableItem>(
              returnValue,
              new ActionableItem() {
                @NonNull
                @Override
                public Observable<InteractorEvent> lifecycle() {
                  return interactorLifecycleSubject;
                }
              })));
  returnValueSubject.onComplete();

  testSubscriber.assertNoValues();
  testSubscriber.assertNoErrors();
  testSubscriber.assertNotComplete();

  interactorLifecycleSubject.onNext(InteractorEvent.ACTIVE);

  testSubscriber.assertValueCount(1);
  assertThat(testSubscriber.values().get(0).get().getValue()).isEqualTo(returnValue);
  testSubscriber.assertComplete();
  testSubscriber.assertNoErrors();
}
 
Example 15
Source File: ExceptionHandlingIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenSubscriberAndException_whenHandleOnException_thenResumed() {
    TestObserver<String> testObserver = new TestObserver<>();

    Observable
      .<String>error(UNKNOWN_EXCEPTION)
      .onExceptionResumeNext(Observable.just("exceptionResumed"))
      .subscribe(testObserver);

    testObserver.assertNoErrors();
    testObserver.assertComplete();
    testObserver.assertValueCount(1);
    testObserver.assertValue("exceptionResumed");
}
 
Example 16
Source File: FactorServiceTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldFindById() {
    when(factorRepository.findById("my-factor")).thenReturn(Maybe.just(new Factor()));
    TestObserver testObserver = factorService.findById("my-factor").test();

    testObserver.awaitTerminalEvent();
    testObserver.assertComplete();
    testObserver.assertNoErrors();
    testObserver.assertValueCount(1);
}
 
Example 17
Source File: RxCommandTest.java    From RxCommand with MIT License 5 votes vote down vote up
@Test
public void switchToLatest_allowingConcurrent_onlyLatestValue() {
    RxCommand<String> command = RxCommand.create(o -> Observable.just((String) o)
            .subscribeOn(Schedulers.newThread())
            .delay(10, TimeUnit.MILLISECONDS)
    );

    // allows concurrent
    command.setAllowsConcurrentExecution(true);

    TestObserver<String> testObserver = new TestObserver<>();
    command.switchToLatest().subscribe(testObserver);

    command.execute("1");
    command.execute("2");
    command.execute("3");

    // wait
    try {
        Thread.sleep(30);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    testObserver.assertValueCount(1);
    testObserver.assertValue("3");

}
 
Example 18
Source File: GodEyeHelperTest.java    From AndroidGodEye with Apache License 2.0 5 votes vote down vote up
@Test
public void onPageLoadedSuccessForActivity() {
    try {
        GodEye.instance().uninstall();
        GodEye.instance().install(GodEyeConfig.noneConfigBuilder().withPageloadConfig(new PageloadConfig()).build());
        ActivityController<Test1Activity> activityController = Robolectric.buildActivity(Test1Activity.class).create().start().resume();
        Test1Activity activity = activityController.get();
        TestObserver testObserver = GodEye.instance().<Pageload, PageLifecycleEventInfo>moduleObservable(GodEye.ModuleName.PAGELOAD).test();
        GodEyeHelper.onPageLoaded(activity);
        activityController.pause().stop().destroy();
        Shadows.shadowOf(ThreadUtil.obtainHandler("godeye-pageload").getLooper()).getScheduler().advanceToNextPostedRunnable();

        List<TestPageEvent> testPageEvents = new ArrayList<>();
        testPageEvents.add(new TestPageEvent(activity.hashCode(), ActivityLifecycleEvent.ON_CREATE, 1));
        testPageEvents.add(new TestPageEvent(activity.hashCode(), ActivityLifecycleEvent.ON_START, 2));
        testPageEvents.add(new TestPageEvent(activity.hashCode(), ActivityLifecycleEvent.ON_DRAW, 3));
        testPageEvents.add(new TestPageEvent(activity.hashCode(), ActivityLifecycleEvent.ON_RESUME, 4));
        testPageEvents.add(new TestPageEvent(activity.hashCode(), ActivityLifecycleEvent.ON_LOAD, 5));
        testPageEvents.add(new TestPageEvent(activity.hashCode(), ActivityLifecycleEvent.ON_PAUSE, 6));
        testPageEvents.add(new TestPageEvent(activity.hashCode(), ActivityLifecycleEvent.ON_STOP, 7));
        testPageEvents.add(new TestPageEvent(activity.hashCode(), ActivityLifecycleEvent.ON_DESTROY, 8));
        testObserver.assertValueCount(8);
        for (int i = 0; i < 8; i++) {
            int finalI = i;
            testObserver.assertValueAt(i, new Predicate<PageLifecycleEventInfo>() {
                @Override
                public boolean test(PageLifecycleEventInfo o) throws Exception {
                    return testPageEvents.get(finalI).pageHashCode == o.pageInfo.pageHashCode
                            && testPageEvents.get(finalI).allEventSize == o.allEvents.size()
                            && testPageEvents.get(finalI).lifecycleEvent.equals(o.currentEvent.lifecycleEvent);
                }
            });
        }
    } catch (UninstallException e) {
        fail();
    }
}
 
Example 19
Source File: FingerprintAuthenticationTest.java    From RxFingerprint with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthenticationSuccessfulOnSecondTry() throws Exception {
    when(fingerprintApiWrapper.isUnavailable()).thenReturn(false);
    when(fingerprintApiWrapper.getFingerprintManager()).thenReturn(fingerprintManager);

    TestObserver<FingerprintAuthenticationResult> testObserver = observable.test();

    ArgumentCaptor<FingerprintManager.AuthenticationCallback> callbackCaptor = ArgumentCaptor.forClass(FingerprintManager.AuthenticationCallback.class);
    verify(fingerprintManager).authenticate(any(CryptoObject.class), any(CancellationSignal.class), anyInt(), callbackCaptor.capture(), any(Handler.class));
    callbackCaptor.getValue().onAuthenticationHelp(0, MESSAGE_HELP);

    testObserver.assertNotTerminated();
    testObserver.assertNoErrors();
    testObserver.assertNotComplete();
    testObserver.assertValueCount(1);

    FingerprintAuthenticationResult helpResult = testObserver.values().get(0);
    assertTrue("Authentication should not be successful", !helpResult.isSuccess());
    assertTrue("Result should be equal HELP", helpResult.getResult().equals(FingerprintResult.HELP));
    assertTrue("Should contain help message", helpResult.getMessage().equals(MESSAGE_HELP));

    callbackCaptor.getValue().onAuthenticationSucceeded(mock(AuthenticationResult.class));

    testObserver.awaitTerminalEvent();
    testObserver.assertNoErrors();
    testObserver.assertComplete();
    testObserver.assertValueCount(2);

    FingerprintAuthenticationResult successResult = testObserver.values().get(1);
    assertTrue("Authentication should be successful", successResult.isSuccess());
    assertTrue("Result should be equal AUTHENTICATED", successResult.getResult().equals(FingerprintResult.AUTHENTICATED));
    assertTrue("Should contain no message", successResult.getMessage() == null);
}
 
Example 20
Source File: RxFirebaseDatabaseTest.java    From rxfirebase with Apache License 2.0 4 votes vote down vote up
@Test
public void testDataOfClazz_Query() {
    TestObserver<String> sub = TestObserver.create();

    RxFirebaseDatabase.dataOf(mockQuery, String.class)
            .subscribe(sub);

    verifyQueryAddListenerForSingleValueEvent();
    callValueEventOnDataChange("Foo");

    sub.assertComplete();
    sub.assertNoErrors();

    sub.assertValue("Foo");

    sub.dispose();

    callValueEventOnDataChange("Foo");

    // Ensure no more values are emitted after unsubscribe
    sub.assertValueCount(1);
}