LiveData Testing

General

Category
Free
Tag
TDD & BDD
License
Apache License, Version 2.0
Min SDK
19 (Android 4.4 KitKat)
Registered
Oct 22, 2018
Favorites
1
Link
https://github.com/jraska/livedata-testing
See also
Spek
JUnit
AndroidUnitTest
JGiven
JDave

Additional

Language
Java
Version
1.2.0 (May 26, 2021)
Created
Jul 18, 2018
Updated
Feb 28, 2022
Owner
Josef Raska (jraska)
Contributors
Josef Raska (jraska)
dependabot[bot]
dependabot-preview[bot]
IMLUNCH (jhamin0511)
4
Activity
Badge
Generate
Download
Source code

Show card

LiveData Testing

TestObserver to easily test LiveData and make assertions on them.

Read Medium Article for more info.

Usage

Having LiveData<Integer> of counter from 0 to 4:

Kotlin - see ExampleTest.kt

liveData.test()
  .awaitValue()
  .assertHasValue()
  .assertValue { it > 3 }
  .assertValue(4)
  .assertHistorySize(5)
  .assertNever { it > 4 }


// Assertion on structures with a lot of nesting
viewLiveData.map { it.items[0].header.title }
  .assertValue("Expected title")

Java - see ExampleTest.java

TestObserver.test(liveData)
  .awaitValue()
  .assertHasValue()
  .assertValue(value -> value > 3)
  .assertValue(4)
  .assertHistorySize(5)
  .assertNever(value -> value > 4);

Don't forget to use InstantTaskExecutorRule from androidx.arch.core:core-testing to make your LiveData test run properly.

Download

Kotlin users:
testImplementation 'com.jraska.livedata:testing-ktx:1.2.0'
Java users:
testImplementation 'com.jraska.livedata:testing:1.2.0'

Philosophy

This library is created in a belief that to effective and valuable test should be fast to write and model real code usage. As by Architecture components spec Activity should communicate with its ViewModel only through observing LiveData. TestObserver in this case simulates the Activity and by testing LiveData, we could test our whole logic except the View where the responsibility belongs to Activity. Key ideas:

  • Test pretends to be an Activity
  • No Android framework mocking or Robolectric - just standard fast JUnit tests
  • Fluent API inspired by RxJava TestObserver
  • Easy to write fast executing tests - possibly TDD