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

The following examples show how to use io.reactivex.observers.TestObserver#assertNoValues() . 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: RxFirebaseStorageTest.java    From rxfirebase with Apache License 2.0 6 votes vote down vote up
@Test public void testPutFile_notSuccessful() {
  mockNotSuccessfulResultForTask(mockUploadTask, new IllegalStateException());
  when(mockStorageReference.putFile(mockUri)).thenReturn(mockUploadTask);

  TestObserver<UploadTask.TaskSnapshot> obs = TestObserver.create();

  RxFirebaseStorage.putFile(mockStorageReference, mockUri).subscribe(obs);
  verifyAddOnCompleteListenerForTask(mockUploadTask);

  callOnComplete(mockUploadTask);
  obs.dispose();

  callOnComplete(mockUploadTask);

  obs.assertError(IllegalStateException.class);
  obs.assertNoValues();
}
 
Example 2
Source File: OnErrorRetryIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenSubscriberAndError_whenRetryWhenOnError_thenResubscribed() {
    TestObserver<String> testObserver = new TestObserver<>();
    AtomicInteger atomicCounter = new AtomicInteger(0);

    Observable
      .<String>error(() -> {
          atomicCounter.incrementAndGet();
          return UNKNOWN_ERROR;
      })
      .retryWhen(throwableObservable -> Observable.just("anything"))
      .subscribe(testObserver);

    testObserver.assertNoErrors();
    testObserver.assertComplete();
    testObserver.assertNoValues();
    assertTrue("should retry once", atomicCounter.get() == 1);
}
 
Example 3
Source File: PreparedDeleteByQueryTest.java    From storio with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPerformDeletionByQueryCompletable() {
    final DeleteByQueryStub stub = new DeleteByQueryStub();

    final TestObserver<DeleteResult> testObserver = new TestObserver<DeleteResult>();

    new PreparedDeleteByQuery.Builder(stub.storIOSQLite, stub.deleteQuery)
            .withDeleteResolver(stub.deleteResolver)
            .prepare()
            .asRxCompletable()
            .subscribe(testObserver);

    testObserver.awaitTerminalEvent();
    testObserver.assertNoErrors();
    testObserver.assertNoValues();

    verify(stub.storIOSQLite).defaultRxScheduler();
    stub.verifyBehaviour();
}
 
Example 4
Source File: OnErrorRetryIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenSubscriberAndError_whenRetryWhenOnError_thenCompleted() {
    TestObserver<String> testObserver = new TestObserver<>();
    AtomicInteger atomicCounter = new AtomicInteger(0);

    Observable
      .<String>error(() -> {
          atomicCounter.incrementAndGet();
          return UNKNOWN_ERROR;
      })
      .retryWhen(throwableObservable -> Observable.empty())
      .subscribe(testObserver);

    testObserver.assertNoErrors();
    testObserver.assertComplete();
    testObserver.assertNoValues();
    assertTrue("should not retry", atomicCounter.get() == 0);
}
 
Example 5
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_Then_Get_Error_Single()
    throws NoSuchMethodException, IOException {
  Method method = Providers.class.getDeclaredMethod("single");
  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(), metadata);
  TestObserver<List<Mock>> subscriber = single.test();

  subscriber.awaitTerminalEvent();
  subscriber.assertNoValues();

  HttpException httpException = (HttpException) subscriber.errors().get(0);
  assertThat(httpException.getMessage(), is("HTTP 404 null"));
}
 
Example 6
Source File: RxFirebaseAuthTest.java    From rxfirebase with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateUserWithEmailAndPassword_NotSuccessful() {
    when(mockFirebaseUser.getEmail())
            .thenReturn("[email protected]");

    mockNotSuccessfulResult(new IllegalStateException());

    when(mockFirebaseAuth.createUserWithEmailAndPassword("[email protected]", "password"))
            .thenReturn(mockAuthResultTask);

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

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

    callOnComplete(mockAuthResultTask);
    obs.dispose();

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

    obs.assertError(IllegalStateException.class);
    obs.assertNoValues();
}
 
Example 7
Source File: PreparedPutCollectionOfObjectsTest.java    From storio with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldThrowExceptionIfNoTypeMappingWasFoundWithTransactionWithoutAffectingDbAsCompletable() {
    final StorIOSQLite storIOSQLite = mock(StorIOSQLite.class);
    final StorIOSQLite.LowLevel lowLevel = mock(StorIOSQLite.LowLevel.class);

    when(storIOSQLite.lowLevel()).thenReturn(lowLevel);

    when(storIOSQLite.put()).thenReturn(new PreparedPut.Builder(storIOSQLite));

    final List<TestItem> items = asList(TestItem.newInstance(), TestItem.newInstance());

    final TestObserver<PutResults<TestItem>> testObserver = new TestObserver<PutResults<TestItem>>();

    storIOSQLite
            .put()
            .objects(items)
            .useTransaction(true)
            .prepare()
            .asRxCompletable()
            .subscribe(testObserver);

    testObserver.awaitTerminalEvent();
    testObserver.assertNoValues();
    assertThat(testObserver.errors().get(0))
            .isInstanceOf(StorIOException.class)
            .hasCauseInstanceOf(IllegalStateException.class);

    verify(storIOSQLite).put();
    verify(storIOSQLite).lowLevel();
    verify(storIOSQLite).defaultRxScheduler();
    verify(storIOSQLite).interceptors();
    verify(lowLevel).typeMapping(TestItem.class);
    verify(lowLevel, never()).insert(any(InsertQuery.class), any(ContentValues.class));
    verify(lowLevel, never()).update(any(UpdateQuery.class), any(ContentValues.class));
    verifyNoMoreInteractions(storIOSQLite, lowLevel);
}
 
Example 8
Source File: ScopeServiceTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldFindById_notExistingScope() {
    when(scopeRepository.findById("my-scope")).thenReturn(Maybe.empty());
    TestObserver testObserver = scopeService.findById("my-scope").test();
    testObserver.awaitTerminalEvent();

    testObserver.assertNoValues();
}
 
Example 9
Source File: PreparedGetObjectTest.java    From storio with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldThrowExceptionIfNoTypeMappingWasFoundWithoutAccessingDbWithRawQueryAsMaybe() {
    final StorIOSQLite storIOSQLite = mock(StorIOSQLite.class);
    final StorIOSQLite.LowLevel lowLevel = mock(StorIOSQLite.LowLevel.class);

    when(storIOSQLite.get()).thenReturn(new PreparedGet.Builder(storIOSQLite));
    when(storIOSQLite.lowLevel()).thenReturn(lowLevel);

    final TestObserver<TestItem> testObserver = new TestObserver<TestItem>();

    storIOSQLite
            .get()
            .object(TestItem.class)
            .withQuery(RawQuery.builder().query("test query").build())
            .prepare()
            .asRxMaybe()
            .subscribe(testObserver);

    testObserver.awaitTerminalEvent();
    testObserver.assertNoValues();
    Throwable error = testObserver.errors().get(0);

    assertThat(error)
            .isInstanceOf(StorIOException.class)
            .hasCauseInstanceOf(IllegalStateException.class)
            .hasMessage("Error has occurred during Get operation. query = RawQuery{query='test query', args=[], affectsTables=[], affectsTags=[], observesTables=[], observesTags=[]}");

    assertThat(error.getCause())
            .hasMessage("This type does not have type mapping: "
                    + "type = " + TestItem.class + "," +
                    "db was not touched by this operation, please add type mapping for this type");

    verify(storIOSQLite).get();
    verify(storIOSQLite).lowLevel();
    verify(storIOSQLite).defaultRxScheduler();
    verify(storIOSQLite).interceptors();
    verify(lowLevel).typeMapping(TestItem.class);
    verify(lowLevel, never()).rawQuery(any(RawQuery.class));
    verifyNoMoreInteractions(storIOSQLite, lowLevel);
}
 
Example 10
Source File: EmailTemplateServiceTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldFindByDomainAndTemplate_notExistingEmail() {
    when(emailRepository.findByTemplate(ReferenceType.DOMAIN, DOMAIN, Template.LOGIN.template())).thenReturn(Maybe.empty());
    TestObserver testObserver = emailTemplateService.findByDomainAndTemplate(DOMAIN, Template.LOGIN.template()).test();
    testObserver.awaitTerminalEvent();

    testObserver.assertNoValues();
}
 
Example 11
Source File: ClientServiceTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void findByClientIdAndDomain() {
    when(applicationService.findByDomainAndClientId(DOMAIN, "my-client")).thenReturn(Maybe.empty());
    TestObserver testObserver = clientService.findByDomainAndClientId(DOMAIN, "my-client").test();
    testObserver.awaitTerminalEvent();

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

  interactorLifecycleSubject.onNext(InteractorEvent.ACTIVE);

  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.assertValueCount(1);
  assertThat(testSubscriber.values().get(0).get().getValue()).isEqualTo(returnValue);
  testSubscriber.assertComplete();
  testSubscriber.assertNoErrors();
}
 
Example 13
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 14
Source File: RxCommandTest.java    From RxCommand with MIT License 5 votes vote down vote up
@Test
public void anErrorOccurredDuringExecution_noValue() {
    final Throwable throwable = new Exception("something wrong");
    RxCommand<String> command = RxCommand.create(o -> Observable.error(throwable));

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

    command.execute(null);

    testObserver.assertNoValues();
    testObserver.assertNoErrors();
    testObserver.assertNotComplete();
}
 
Example 15
Source File: PreparedGetObjectTest.java    From storio with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldThrowExceptionIfNoTypeMappingWasFoundWithoutAccessingDbWithRawQueryAsSingle() {
    final StorIOSQLite storIOSQLite = mock(StorIOSQLite.class);
    final StorIOSQLite.LowLevel lowLevel = mock(StorIOSQLite.LowLevel.class);

    when(storIOSQLite.get()).thenReturn(new PreparedGet.Builder(storIOSQLite));
    when(storIOSQLite.lowLevel()).thenReturn(lowLevel);

    final TestObserver<Optional<TestItem>> testObserver = new TestObserver<Optional<TestItem>>();

    storIOSQLite
            .get()
            .object(TestItem.class)
            .withQuery(RawQuery.builder().query("test query").build())
            .prepare()
            .asRxSingle()
            .subscribe(testObserver);

    testObserver.awaitTerminalEvent();
    testObserver.assertNoValues();
    Throwable error = testObserver.errors().get(0);

    assertThat(error)
            .isInstanceOf(StorIOException.class)
            .hasCauseInstanceOf(IllegalStateException.class)
            .hasMessage("Error has occurred during Get operation. query = RawQuery{query='test query', args=[], affectsTables=[], affectsTags=[], observesTables=[], observesTags=[]}");

    assertThat(error.getCause())
            .hasMessage("This type does not have type mapping: "
                    + "type = " + TestItem.class + "," +
                    "db was not touched by this operation, please add type mapping for this type");

    verify(storIOSQLite).get();
    verify(storIOSQLite).lowLevel();
    verify(storIOSQLite).defaultRxScheduler();
    verify(storIOSQLite).interceptors();
    verify(lowLevel).typeMapping(TestItem.class);
    verify(lowLevel, never()).rawQuery(any(RawQuery.class));
    verifyNoMoreInteractions(storIOSQLite, lowLevel);
}
 
Example 16
Source File: RxFirebaseDatabaseTest.java    From rxfirebase with Apache License 2.0 4 votes vote down vote up
@Test
public void testData_DataReference_onCancelled() {
    TestObserver<DataSnapshot> sub = TestObserver.create();

    RxFirebaseDatabase.data(mockDatabaseReference)
            .subscribe(sub);

    verifyDataReferenceAddListenerForSingleValueEvent();
    callValueEventOnCancelled(new DatabaseException("foo"));

    sub.assertError(DatabaseException.class);
    sub.assertNoValues();

    sub.dispose();

    callValueEventOnCancelled(new DatabaseException("foo"));

    // Ensure no more values are emitted after unsubscribe
    assertThat(sub.errorCount())
            .isEqualTo(1);

}
 
Example 17
Source File: PreparedGetObjectTest.java    From storio with Apache License 2.0 4 votes vote down vote up
@Test
public void cursorMustBeClosedInCaseOfExceptionForSingle() {
    final StorIOSQLite storIOSQLite = mock(StorIOSQLite.class);

    //noinspection unchecked
    final GetResolver<Object> getResolver = mock(GetResolver.class);

    final Cursor cursor = mock(Cursor.class);

    when(cursor.getCount()).thenReturn(10);

    when(cursor.moveToNext()).thenReturn(true);

    when(getResolver.performGet(eq(storIOSQLite), any(Query.class)))
            .thenReturn(cursor);

    when(getResolver.mapFromCursor(storIOSQLite, cursor))
            .thenThrow(new IllegalStateException("test exception"));

    PreparedGetObject<Object> preparedGetObject =
            new PreparedGetObject<Object>(
                    storIOSQLite,
                    Object.class,
                    Query.builder().table("test_table").build(),
                    getResolver
            );

    final TestObserver<Object> testObserver = new TestObserver<Object>();

    preparedGetObject
            .asRxSingle()
            .subscribe(testObserver);

    testObserver.awaitTerminalEvent();

    testObserver.assertNoValues();
    testObserver.assertError(StorIOException.class);

    StorIOException storIOException = (StorIOException) testObserver.errors().get(0);

    IllegalStateException cause = (IllegalStateException) storIOException.getCause();
    assertThat(cause).hasMessage("test exception");

    // Cursor must be closed in case of exception
    verify(cursor).close();

    //noinspection unchecked
    verify(getResolver).performGet(eq(storIOSQLite), any(Query.class));
    verify(getResolver).mapFromCursor(storIOSQLite, cursor);
    verify(cursor).getCount();
    verify(cursor).moveToNext();
    verify(storIOSQLite).defaultRxScheduler();
    verify(storIOSQLite).interceptors();

    verifyNoMoreInteractions(storIOSQLite, getResolver, cursor);
}
 
Example 18
Source File: RxFirebaseStorageTest.java    From rxfirebase with Apache License 2.0 4 votes vote down vote up
@Test public void testGetBytes_notSuccessful() {
  mockNotSuccessfulResultForTask(mockBytesTask, new IllegalStateException());
  when(mockStorageReference.getBytes(3)).thenReturn(mockBytesTask);

  TestObserver<byte[]> obs = TestObserver.create();

  RxFirebaseStorage.getBytes(mockStorageReference, 3).subscribe(obs);

  verifyAddOnCompleteListenerForTask(mockBytesTask);

  callOnComplete(mockBytesTask);
  obs.dispose();

  callOnComplete(mockBytesTask);

  obs.assertError(IllegalStateException.class);
  obs.assertNoValues();
}
 
Example 19
Source File: PreparedPutContentValuesIterableTest.java    From storio with Apache License 2.0 4 votes vote down vote up
@Test
public void verifyBehaviorInCaseOfExceptionWithoutTransactionSingle() {
    final StorIOSQLite storIOSQLite = mock(StorIOSQLite.class);
    final StorIOSQLite.LowLevel lowLevel = mock(StorIOSQLite.LowLevel.class);

    //noinspection unchecked
    final PutResolver<ContentValues> putResolver = mock(PutResolver.class);

    final List<ContentValues> contentValues = singletonList(mock(ContentValues.class));

    when(putResolver.performPut(same(storIOSQLite), any(ContentValues.class)))
            .thenThrow(new IllegalStateException("test exception"));

    final TestObserver<PutResults<ContentValues>> testObserver = new TestObserver<PutResults<ContentValues>>();

    new PreparedPutContentValuesIterable.Builder(storIOSQLite, contentValues)
            .withPutResolver(putResolver)
            .useTransaction(false)
            .prepare()
            .asRxSingle()
            .subscribe(testObserver);

    testObserver.awaitTerminalEvent();
    testObserver.assertNoValues();
    testObserver.assertError(StorIOException.class);

    //noinspection ThrowableResultOfMethodCallIgnored
    StorIOException expected = (StorIOException) testObserver.errors().get(0);

    IllegalStateException cause = (IllegalStateException) expected.getCause();
    assertThat(cause).hasMessage("test exception");

    // Main check of this test
    verify(lowLevel, never()).endTransaction();

    verify(storIOSQLite).lowLevel();
    verify(storIOSQLite).defaultRxScheduler();
    verify(storIOSQLite).interceptors();
    verify(putResolver).performPut(same(storIOSQLite), any(ContentValues.class));
    verifyNoMoreInteractions(storIOSQLite, lowLevel, putResolver);
}
 
Example 20
Source File: PreparedGetObjectTest.java    From storio with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void shouldThrowExceptionIfNoTypeMappingWasFoundWithoutAccessingDbWithQueryAsSingle() {
    final StorIOSQLite storIOSQLite = mock(StorIOSQLite.class);
    final StorIOSQLite.LowLevel lowLevel = mock(StorIOSQLite.LowLevel.class);

    when(storIOSQLite.get()).thenReturn(new PreparedGet.Builder(storIOSQLite));
    when(storIOSQLite.lowLevel()).thenReturn(lowLevel);

    final TestObserver<Optional<TestItem>> testObserver = new TestObserver<Optional<TestItem>>();

    storIOSQLite
            .get()
            .object(TestItem.class)
            .withQuery(Query.builder().table("test_table").build())
            .prepare()
            .asRxSingle()
            .subscribe(testObserver);

    testObserver.awaitTerminalEvent();
    testObserver.assertNoValues();
    Throwable error = testObserver.errors().get(0);

    assertThat(error)
            .isInstanceOf(StorIOException.class)
            .hasCauseInstanceOf(IllegalStateException.class)
            .hasMessage("Error has occurred during Get operation. query = Query{distinct=false, table='test_table', columns=[], where='', whereArgs=[], groupBy='', having='', orderBy='', limit='', observesTags='[]'}");

    assertThat(error.getCause())
            .hasMessage("This type does not have type mapping: "
                    + "type = " + TestItem.class + "," +
                    "db was not touched by this operation, please add type mapping for this type");

    verify(storIOSQLite).get();
    verify(storIOSQLite).lowLevel();
    verify(storIOSQLite).defaultRxScheduler();
    verify(storIOSQLite).interceptors();
    verify(lowLevel).typeMapping(TestItem.class);
    verify(lowLevel, never()).query(any(Query.class));
    verifyNoMoreInteractions(storIOSQLite, lowLevel);
}