Last active
March 21, 2016 08:16
-
-
Save fly1tkg/3c29dc34682b64076058 to your computer and use it in GitHub Desktop.
RxJavaのテストコードのサンプル http://fly1tkg.github.io/2016/03/rxjava-test/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.junit.Test; | |
import java.util.Arrays; | |
import rx.Observable; | |
import rx.observers.TestSubscriber; | |
public class RxJavaUnitTest { | |
@Test | |
public void observableTest() throws Exception { | |
Observable<String> observable = Observable.just("foo").flatMap(); | |
// Testsubscriberを作成する | |
TestSubscriber<String> testSubscriber = new TestSubscriber<>(); | |
// テストしたObservableに先程のSubscriberをsubscribeさせます | |
observable.subscribe(testSubscriber); | |
// 処理が完了するのを待ちます | |
testSubscriber.awaitTerminalEvent(); | |
// 検証します | |
testSubscriber.assertNoErrors(); | |
testSubscriber.assertValue("foo"); | |
} | |
@Test | |
public void observableAssertError() throws Exception { | |
Observable<String> observable = Observable.error(new IllegalStateException()); | |
TestSubscriber<String> testSubscriber = new TestSubscriber<>(); | |
observable.subscribe(testSubscriber); | |
testSubscriber.awaitTerminalEvent(); | |
// onErrorに渡ってきた例外を検証する | |
testSubscriber.assertError(IllegalStateException.class); | |
} | |
@Test | |
public void streamAssert() throws Exception { | |
TestSubscriber<Integer> testSubscriber = new TestSubscriber<>(); | |
// onNextに値が渡っていないことを検証できます | |
testSubscriber.assertNoValues(); | |
testSubscriber.onNext(1); | |
// onNextに渡ってきた値を検証する | |
assert(1 == testSubscriber.getOnNextEvents().get(0)); | |
testSubscriber.onNext(2); | |
testSubscriber.onNext(3); | |
// getOnNextEventsはonNextで受け取った値を全て保持しています | |
assert(1 == testSubscriber.getOnNextEvents().get(0)); | |
assert(2 == testSubscriber.getOnNextEvents().get(1)); | |
assert(3 == testSubscriber.getOnNextEvents().get(2)); | |
// onNextで受け取った値の配列を検証できます | |
testSubscriber.assertReceivedOnNext(Arrays.asList(1, 2, 3)); | |
// 受け取った値の数を検証できます | |
testSubscriber.assertValueCount(3); | |
// subscriberの状態も検証できる | |
testSubscriber.assertNotCompleted(); | |
testSubscriber.assertNoTerminalEvent(); | |
testSubscriber.onCompleted(); | |
testSubscriber.assertTerminalEvent(); | |
testSubscriber.unsubscribe(); | |
testSubscriber.assertUnsubscribed(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment