Upload
simon-percic
View
139
Download
0
Embed Size (px)
Citation preview
Best practices for unit testing RxJava
Simon Perčič, senior Android developer
Tuesday, November 8th, 2016 @ 18:00
RxJava?
● Useful for combining, transforming, manipulating streams of data
● How to unit test?
What to unit test?
● Observables - composition of operators
● Code that uses Rx (e.g. presenters)
Let’s set an example
What will we test?
What will we test?
DataManager methods:
Tip #1 (testability)
Tip #1Separate data providers
Test skeleton 1/3
mocked
subject of testing
Test skeleton 2/3
Test skeleton 3/3
Test examples*
* not best practices
Wrong test #1
Works. → But only if getPlanets() is run on the immediate thread
Wrong test #1
Works. → But only if getPlanets() is run on the immediate thread
Not immediate thread
Runs on another thread!
Wrong test #1 - on another thread
Fails. → getPlanets() switches thread, Assert happens “too soon”
Wrong test #2 - blocking
Works. → it waits for the getPlanets() single to complete.
Wrong test #2 - countdown
Blocks here
Tip #2 (threading)
Tip #2
Single / Observable transformer
Network thread
Tip #2 - in manager
Compose with scheduler transformer
Tip #2 - in test
No op transformation.
Tip #3 (the big one)*
* best practices
Built-in classes
● TestSubscriber
● TestScheduler
● TestSubject
Tip #3 [1/3] - TestSubscriber
● Subscriber with additional test methods
● Part of RxJava
TestSubscriber example
● Blocking○ awaitTerminalEvent()
TestSubscriber methods
Will block
● Assertions○ Completion
■ assertCompleted() / assertNotCompleted()■ assertTerminalEvent() / assertNoTerminalEvent()
TestSubscriber methods
● Assertions○ Errors
■ assertNoErrors()■ assertError(Class / Throwable)
TestSubscriber methods
● Assertions○ Values
■ assertNoValues()■ assertValueCount(int)■ assertValue(T) / assertValues(T…)
TestSubscriber methods
● Get values○ Values
■ List<T> getOnNextEvents()○ Errors
■ List<Throwable> getOnErrorEvents()
TestSubscriber methods
Tip #3 [2/3] - TestScheduler
● Time “manipulation”○ Advance time
■ advanceTimeBy(long, TimeUnit)■ advanceTimeTo (long, TimeUnit)
○ Force trigger■ triggerActions()
TestScheduler methods
Tip #3 [3/3] - TestSubject
● Enables us to queue events with a delay○ onNext(T, delayMs)○ onCompleted(delayMs)○ onError(Throwable, delayMs)
TestSubject - setup
TestSubject - test
● Use RxJava
● Make your code unit-testable
● Be aware of threading
● Use built-in testing utils
Recap
Questions?
@simonpercic @simonpercicsimonpercic