Anti-pattern for testing RxJava code

Posted by & filed under , .

iStock_blog write keyboardThis is an obvious one but I find myself so often using it and every single time it means I have to spend extra time debugging my test / code until I realize that I’ve fallen for the same mistake again. I’m using RxJava here and using Groovy and Spock framework for testing — and you could argue that this might be the crux of the issue, but I could bet good money that something similar can happen when writing pure Java/JUnit unit tests for an RxJava component too.

Let’s start with a simple piece of code:

< pre lang=”java” escaped=”true”>
public class Process {
private StringProcessor stringProcessor;

public Process(StringProcessor stringProcessor) {
this.stringProcessor = stringProcessor;
}

public Observable<String> process(int x) {
return Observable.just(x)
.map(String::valueOf)
.map(stringProcessor::transform)
.doOnNext(System.out::println);
}
}

public interface StringProcessor {
int transform(String s);
}

Nothing wrong with this code, right? It takes an integer and converts it to String and then uses the StringProcessor class to perform some string processing on this then prints it out on console.

Ok now let’s write a Spock unit test for this. Part of this I don’t want to invoke the whole StringProcessor.transform() method — maybe because it’s too heavy for a test or because it might be hard to predict the output (for instance in cases where the implementation relies on time/date etc):

def "ensure zeros get replaced by 9"() {
    def i = 1020
    def proc = Mock(StringProcessor)
    def x = new Process(proc)
 
when:
    def r = x.process(i).toBlocking().single()
 
then:
    1 * proc.transform("$i")
}

Looking at the above you can see that my unit test is interested just in the fact that the tested code converts the integer to string then passes the control to the StringProcessor. And to do so it seems to do the right thing: it creates a mock for the StringProcessor and ensures that it is called exactly once with my integer converted to string. Yet there’s something wrong with this code — and if you run it you will get a NullPointerException!

The reason for it is simple — this line

1 * proc.transform("$i")

doesn’t return anything. Which is equivalent to returning (Observable<>)null — and then in my Process class this null is trying to get applied a .doOnNext which is where it all goes wrong.

The fix is actually trivial:

1 * proc.transform("$i") >> "abcdef" //<-- return here any string you need to return

Then the .doOnNext goes through and your test succeeds. Very small change needed yet as I said it created many times long debugging sessions. If only writing this blog post would help with that 🙂