Search in sources :

Example 16 with TestScheduler

use of rx.schedulers.TestScheduler in project AnDevCon-RxPatterns by colintheshots.

the class Example16Test method using_testscheduler_to_simulate_network_events.

@Test
public void using_testscheduler_to_simulate_network_events() {
    // TestScheduler lets you advance time by hand
    TestScheduler scheduler = Schedulers.test();
    TestSubscriber<NetworkResponse> subscriber = new TestSubscriber<>();
    // Scheduler.Worker lets you schedule events in time
    Scheduler.Worker worker = scheduler.createWorker();
    // Subjects allow both input and output, so they can be swapped in for
    // Retrofit calls to unit test your code.
    final PublishSubject<NetworkResponse> networkSubject = PublishSubject.create();
    // schedule a first observable event to occur at 1000 ms
    worker.schedule(new Action0() {

        @Override
        public void call() {
            // explicitly calling onNext in a worker allows one to
            // create a very specific test of timed events
            networkSubject.onNext(new NetworkResponse(401));
        }
    }, 1000, TimeUnit.MILLISECONDS);
    // schedule a second observable event to occur at 2000 ms
    worker.schedule(new Action0() {

        @Override
        public void call() {
            networkSubject.onNext(new NetworkResponse(200));
            networkSubject.onCompleted();
        }
    }, 2000, TimeUnit.MILLISECONDS);
    // we must subscribe before anticipating results
    networkSubject.subscribeOn(scheduler).subscribe(subscriber);
    // we can manually advance time using the scheduler and check assertions
    scheduler.advanceTimeBy(1500, TimeUnit.MILLISECONDS);
    subscriber.assertReceivedOnNext(Arrays.asList(new NetworkResponse(401)));
    // awaitTerminalEvent will wait forever if we don't advance time enough
    scheduler.advanceTimeBy(500, TimeUnit.MILLISECONDS);
    subscriber.awaitTerminalEvent();
    subscriber.assertReceivedOnNext(Arrays.asList(new NetworkResponse(401), new NetworkResponse(200)));
    // TestSubscriber provides many useful methods
    subscriber.assertNoErrors();
    subscriber.assertValueCount(2);
    subscriber.assertUnsubscribed();
}
Also used : Action0(rx.functions.Action0) TestScheduler(rx.schedulers.TestScheduler) Scheduler(rx.Scheduler) TestSubscriber(rx.observers.TestSubscriber) TestScheduler(rx.schedulers.TestScheduler) Override(java.lang.Override) Test(org.junit.Test)

Example 17 with TestScheduler

use of rx.schedulers.TestScheduler in project AnDevCon-RxPatterns by colintheshots.

the class Example16Test method should_test_observable_interval.

// http://stackoverflow.com/questions/26699147/how-to-use-testscheduler-in-rxjava
@Test
public void should_test_observable_interval() {
    TestScheduler scheduler = new TestScheduler();
    final List<Long> result = new ArrayList<>();
    Observable.interval(1, TimeUnit.SECONDS, scheduler).take(5).subscribe(new Action1<Long>() {

        @Override
        public void call(Long aLong) {
            result.add(aLong);
        }
    });
    assertTrue(result.isEmpty());
    scheduler.advanceTimeBy(2, TimeUnit.SECONDS);
    assertEquals(2, result.size());
    scheduler.advanceTimeBy(10, TimeUnit.SECONDS);
    assertEquals(5, result.size());
}
Also used : Long(java.lang.Long) ArrayList(java.util.ArrayList) TestScheduler(rx.schedulers.TestScheduler) Override(java.lang.Override) Test(org.junit.Test)

Example 18 with TestScheduler

use of rx.schedulers.TestScheduler in project android-oss by kickstarter.

the class SearchViewModelTest method testSearchProjectsWhenEnterSearchTerm.

@Test
public void testSearchProjectsWhenEnterSearchTerm() {
    final TestScheduler scheduler = new TestScheduler();
    final Environment env = environment().toBuilder().scheduler(scheduler).build();
    setUpEnvironment(env);
    // Popular projects emit immediately.
    this.popularProjectsPresent.assertValues(true);
    this.searchProjectsPresent.assertNoValues();
    this.segmentTrack.assertValue(EventName.CTA_CLICKED.getEventName());
    // Searching shouldn't emit values immediately
    this.vm.inputs.search("hello");
    this.searchProjectsPresent.assertNoValues();
    this.segmentTrack.assertValue(EventName.CTA_CLICKED.getEventName());
    // Waiting a small amount time shouldn't emit values
    scheduler.advanceTimeBy(200, TimeUnit.MILLISECONDS);
    this.searchProjectsPresent.assertNoValues();
    this.segmentTrack.assertValue(EventName.CTA_CLICKED.getEventName());
    // Waiting the rest of the time makes the search happen
    scheduler.advanceTimeBy(300, TimeUnit.MILLISECONDS);
    this.searchProjectsPresent.assertValues(false, true);
    scheduler.advanceTimeBy(300, TimeUnit.MILLISECONDS);
    this.segmentTrack.assertValues(EventName.CTA_CLICKED.getEventName());
    // Typing more search terms doesn't emit more values
    this.vm.inputs.search("hello world!");
    this.searchProjectsPresent.assertValues(false, true);
    scheduler.advanceTimeBy(300, TimeUnit.MILLISECONDS);
    this.segmentTrack.assertValues(EventName.CTA_CLICKED.getEventName(), EventName.PAGE_VIEWED.getEventName());
    // Waiting enough time emits search results
    scheduler.advanceTimeBy(500, TimeUnit.MILLISECONDS);
    this.searchProjectsPresent.assertValues(false, true, false, true);
    // Clearing search terms brings back popular projects.
    this.vm.inputs.search("");
    this.searchProjectsPresent.assertValues(false, true, false, true, false);
    this.popularProjectsPresent.assertValues(true, false, true);
}
Also used : Environment(com.kickstarter.libs.Environment) TestScheduler(rx.schedulers.TestScheduler) Test(org.junit.Test)

Example 19 with TestScheduler

use of rx.schedulers.TestScheduler in project android-oss by kickstarter.

the class SearchViewModelTest method testNoResults.

@Test
public void testNoResults() {
    final TestScheduler scheduler = new TestScheduler();
    final List<Project> projects = Arrays.asList();
    final MockApiClient apiClient = new MockApiClient() {

        @Override
        @NonNull
        public Observable<DiscoverEnvelope> fetchProjects(@NonNull final DiscoveryParams params) {
            return Observable.just(DiscoverEnvelopeFactory.discoverEnvelope(projects));
        }
    };
    final Environment env = environment().toBuilder().scheduler(scheduler).apiClient(apiClient).build();
    setUpEnvironment(env);
    // populate search and overcome debounce
    this.vm.inputs.search("__");
    scheduler.advanceTimeBy(300, TimeUnit.MILLISECONDS);
    this.searchProjects.assertValueCount(2);
}
Also used : Project(com.kickstarter.models.Project) DiscoverEnvelope(com.kickstarter.services.apiresponses.DiscoverEnvelope) MockApiClient(com.kickstarter.mock.services.MockApiClient) NonNull(androidx.annotation.NonNull) Environment(com.kickstarter.libs.Environment) TestScheduler(rx.schedulers.TestScheduler) DiscoveryParams(com.kickstarter.services.DiscoveryParams) Test(org.junit.Test)

Example 20 with TestScheduler

use of rx.schedulers.TestScheduler in project android-oss by kickstarter.

the class UpdateViewModelTest method testUpdateViewModel_DeepLinkCommentThread.

@Test
public void testUpdateViewModel_DeepLinkCommentThread() {
    final String postId = "3254626";
    final String commentableId = "Q29tbWVudC0zMzU2MTY4Ng";
    final Update update = UpdateFactory.update();
    final ApiClientType apiClient = new MockApiClient() {

        @Override
        @NonNull
        public Observable<Update> fetchUpdate(@NonNull final String projectParam, @NonNull final String updateParam) {
            return Observable.just(update);
        }
    };
    final TestScheduler testScheduler = new TestScheduler();
    final Environment environment = environment().toBuilder().apiClient(apiClient).scheduler(testScheduler).build();
    final UpdateViewModel.ViewModel vm = new UpdateViewModel.ViewModel(environment);
    final TestSubscriber<Pair<String, Update>> startRootCommentsActivityToDeepLinkThreadActivity = new TestSubscriber<>();
    vm.outputs.startRootCommentsActivityToDeepLinkThreadActivity().subscribe(startRootCommentsActivityToDeepLinkThreadActivity);
    final TestSubscriber<String> webViewUrl = new TestSubscriber<>();
    vm.outputs.webViewUrl().subscribe(webViewUrl);
    final TestSubscriber<Pair<String, Boolean>> deepLinkToThreadActivity = new TestSubscriber<>();
    vm.deepLinkToThreadActivity().subscribe(deepLinkToThreadActivity);
    // Start the intent with a project and update.
    vm.intent(new Intent().putExtra(IntentKey.PROJECT, ProjectFactory.project()).putExtra(IntentKey.UPDATE_POST_ID, postId).putExtra(IntentKey.IS_UPDATE_COMMENT, true).putExtra(IntentKey.COMMENT, commentableId));
    // Initial update index url emits.
    webViewUrl.assertValues(update.urls().web().update());
    deepLinkToThreadActivity.assertValue(Pair.create(commentableId, true));
    vm.inputs.goToCommentsActivityToDeepLinkThreadActivity(commentableId);
    testScheduler.advanceTimeBy(2, TimeUnit.SECONDS);
    startRootCommentsActivityToDeepLinkThreadActivity.assertValue(Pair.create(commentableId, update));
    startRootCommentsActivityToDeepLinkThreadActivity.assertValueCount(1);
}
Also used : MockApiClient(com.kickstarter.mock.services.MockApiClient) Intent(android.content.Intent) Update(com.kickstarter.models.Update) ApiClientType(com.kickstarter.services.ApiClientType) NonNull(androidx.annotation.NonNull) Environment(com.kickstarter.libs.Environment) TestSubscriber(rx.observers.TestSubscriber) TestScheduler(rx.schedulers.TestScheduler) Pair(android.util.Pair) Test(org.junit.Test)

Aggregations

TestScheduler (rx.schedulers.TestScheduler)26 Test (org.junit.Test)23 TestSubscriber (rx.observers.TestSubscriber)12 Environment (com.kickstarter.libs.Environment)11 NonNull (androidx.annotation.NonNull)8 MockApiClient (com.kickstarter.mock.services.MockApiClient)8 Project (com.kickstarter.models.Project)6 DiscoveryParams (com.kickstarter.services.DiscoveryParams)6 DiscoverEnvelope (com.kickstarter.services.apiresponses.DiscoverEnvelope)6 EpisodeHeroNameQuery (com.apollographql.apollo.integration.normalizer.EpisodeHeroNameQuery)3 Override (java.lang.Override)3 List (java.util.List)3 Before (org.junit.Before)3 Subscription (rx.Subscription)3 Action0 (rx.functions.Action0)3 Intent (android.content.Intent)2 Utils.mockResponse (com.apollographql.apollo.Utils.mockResponse)2 Response (com.apollographql.apollo.api.Response)2 Update (com.kickstarter.models.Update)2 ApiClientType (com.kickstarter.services.ApiClientType)2