Mock an Observable Interface
1 min read

Mock an Observable Interface

Mock an Observable Interface

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:

public interface UserDatabase {
    Observable<User> readUser(String username);

where the User model is:

public class User {
    private String name;
    private String password;

    public User(String name, String password) { = name;
        this.password = password;

    public String getName() {
        return name;

    public String getPassword() {
        return password;


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

UserDatabase mockUserDatabase;

Then, my setup() method is:

public void setup() {

    // Mock one user answer
    doAnswer(new Answer<observable<user>>() {
        public Observable<user> answer(InvocationOnMock invocation) throws Throwable {
            return Observable.just(user);

where USER_NAME is a String.

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

public void canGetUser() {
    Observable<User> userObservable = mockUserDatabase.readUser(UserCommon.USER_NAME);

    TestObserver<User> userTestObserver = new TestObserver<>();


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:

    .thenReturn(Observable.just(new User(...)));

This is shorter (if it works) :)