Mock an Observable Interface

Posted by in Software, Tutorial

TL;DR: Use a doAnswer() with a new Answer<Observable<Type>>() if you have to mock observables.

Today I wrote my first test where I had to mock an observable interface:

where the User model is:


In my test class (named UserDatabaseTest), I first mocked the interface:


Then, my setup() method is:

where USER_NAME is a String.

To use it, you need to attach an observer and assert:

This is quite simple.


Note: This I haven’t tried yet, but here it goes…

If you want to return a particular method call, you can use:

This is shorter (if it works) :)


A little experiment: If you find this post and ad below useful, please check the ad out :-)