Skip to content

Custom Matchers

Ruby Lichtenshtein edited this page Apr 12, 2018 · 3 revisions

3 methods for creating custom matchers.

  1. Creating Matcher from scratch.
  2. Wrapping existing matcher.
  3. Combining matchers with And/Or.

1. Creating Matcher From scratch

RxTest provides you function for creating matchers, the function located at:

com.rubylichtenstein.rxtest.matchers.CreateMatcher::createMatcher()

and have 2 parameters

  1. assertion: (BaseTestConsumer<T, U>) -> Boolean - lambda from BaseTestConsumer to boolean, return true for success.
  2. failMessage: String - message in case of failure.

Create matcher signature:

import com.rubylichtenstein.rxtest.matchers.*

fun <T, U : BaseTestConsumer<T, U>> createMatcher(assertion: (BaseTestConsumer<T, U>) -> Boolean,
                                                  failMessage: String)
        : Matcher<BaseTestConsumer<T, U>> {

Examples:

  • Assert emitted more than X values
import com.rubylichtenstein.rxtest.matchers.*

fun <T, U : BaseTestConsumer<T, U>> moreValuesThen(count: Int)
    = createMatcher<T, U>({ it.values().size > count },
                          failMessage = "Emited Less values then $count")
                          
Observable.just("Hello", "RxTest")
        .test {
            it shouldEmit moreValuesThen(1)
        }                          
  • Assert emitted less than X values.
import com.rubylichtenstein.rxtest.matchers.*

fun <T, U : BaseTestConsumer<T, U>> lessValuesThen(count: Int)
    = createMatcher<T, U>({ it.values().size < count },
                          failMessage = "More values then $count")    
                          
Observable.just("Hello", "RxTest")
        .test {
            it shouldEmit lessValuesThen(3)
        }                             

2. Wrap existing matcher

  • Create matcher for observer that not emitted any values yet.
fun <T, U : BaseTestConsumer<T, U>> noValues() = valueCount<T, U>(0)

Observable.empty<String>()
        .test {
            it shouldHave noValues()
        }

3. Combine matchers with And/Or

import com.rubylichtenstein.rxtest.matchers.*

fun <T, U : BaseTestConsumer<T, U>> errorOrComplete(error: Throwable)
            = error<T, U>(error) or complete<T, U>()
import com.rubylichtenstein.rxtest.matchers.*

fun <T, U : BaseTestConsumer<T, U>> valueCountBetween(min: Int, max: Int) 
            = moreValuesThen<T, U>(min) and lessValuesThen<T, U>(max)
You can’t perform that action at this time.