From 36ec9311c28f0b048fc54e7ceef20b5c83720879 Mon Sep 17 00:00:00 2001 From: shreyas Date: Sat, 18 Aug 2018 11:44:14 +0530 Subject: [PATCH] Shreyas Mahajan - Adding unit tests for comparing flatmap and switchmap in RxJava --- .../RxFlatmapAndSwitchmapUnitTest.java | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 rxjava/src/test/java/com/baeldung/rxjava/operators/RxFlatmapAndSwitchmapUnitTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/operators/RxFlatmapAndSwitchmapUnitTest.java b/rxjava/src/test/java/com/baeldung/rxjava/operators/RxFlatmapAndSwitchmapUnitTest.java new file mode 100644 index 0000000000..ade48a2cb9 --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/operators/RxFlatmapAndSwitchmapUnitTest.java @@ -0,0 +1,65 @@ +package com.baeldung.rxjava.operators; + +import io.reactivex.Observable; +import io.reactivex.schedulers.TestScheduler; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import static org.hamcrest.CoreMatchers.hasItems; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +public class RxFlatmapAndSwitchmapUnitTest { + @Test + public void givenObservable_whenFlatmap_shouldAssertAllItemsReturned() { + //given + List actualOutput = new ArrayList<>(); + final TestScheduler scheduler = new TestScheduler(); + final List keywordToSearch = Arrays.asList("b", "bo", "boo", "book", "books"); + + //when + Observable.fromIterable(keywordToSearch) + .flatMap(s -> Observable + .just(s + " FirstResult", s + " SecondResult") + .delay(10, TimeUnit.SECONDS, scheduler)) + .toList() + .doOnSuccess(s -> actualOutput.addAll(s)) + .subscribe(); + + scheduler.advanceTimeBy(1, TimeUnit.MINUTES); + + //then + assertThat(actualOutput, hasItems("b FirstResult", "b SecondResult", + "boo FirstResult", "boo SecondResult", + "bo FirstResult", "bo SecondResult", + "book FirstResult", "book SecondResult", + "books FirstResult", "books SecondResult")); + } + + @Test + public void givenObservable_whenSwitchmap_shouldAssertLatestItemReturned() { + //given + List actualOutput = new ArrayList<>(); + final TestScheduler scheduler = new TestScheduler(); + final List keywordToSearch = Arrays.asList("b", "bo", "boo", "book", "books"); + + //when + Observable.fromIterable(keywordToSearch) + .switchMap(s -> Observable + .just(s + " FirstResult", s + " SecondResult") + .delay(10, TimeUnit.SECONDS, scheduler)) + .toList() + .doOnSuccess(s -> actualOutput.addAll(s)) + .subscribe(); + + scheduler.advanceTimeBy(1, TimeUnit.MINUTES); + + //then + assertEquals(2, actualOutput.size()); + assertThat(actualOutput, hasItems("books FirstResult", "books SecondResult")); + } +}