powerj1984
powerj1984

Reputation: 2226

Unit Testing Android app that relies on Robolectric / RxJava / RxAndroid

I am using the Robolectric 3.0 snapshot.

I have a test:

@Test
public void my_test() throws Exception {
        when(testReferenceManager.getUserServiceMock().checkUsernameAvailability(anyString())).thenReturn(Observable.just(Arrays.asList(new User("[email protected]", "password"))));
        when(testReferenceManager.getUserServiceMock().checkAuthStatus(anyString())).thenReturn(Observable.just(Arrays.asList(new User("[email protected]", "password"))));

        EditText emailText = (EditText)activity.findViewById(R.id.text_email);
        EditText passwordText = (EditText)activity.findViewById(R.id.text_password);
        Button signInButton = (Button)activity.findViewById(R.id.sign_in_button);


        emailText.setText("[email protected]");
        passwordText.setText("password");

        Robolectric.flushBackgroundScheduler();
        Robolectric.flushForegroundScheduler();    

        assertThat(signInButton.getText()).isEqualTo(App.R.getString(R.string.button_login));
}

The key thing here is that if the API reports a user exists (which it does from the mocks above) the sign in button text should be the same as the value of the string resource named R.string.button_login.

The setup for changing the button state is done in my Activity like this:

        ReactiveEditText.textObservableForTextView(emailText)
            .startWith(emailText.getText().toString())
            .switchMap(new Func1<String, Observable<Boolean>>() {
                @Override
                public Observable<Boolean> call(String username) {
                    return webServices.usernameAvailable(username);
                }
            })
            .subscribe(new EndlessObserver<Boolean>() {
                @Override
                public void onNext(Boolean available) {
                    if (available) {
                        signInButton.setText(getString(R.string.button_signup));
                    } else {
                        signInButton.setText(getString(R.string.button_login));
                    }
                }
            });

ReactiveEditText.textObservableForTextView simply wraps the textChangedListener interface in a reactive fashion:

public static Observable<String> textObservableForTextView(final TextView tv) {
        Observable<String> textObservable = Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(final Subscriber<? super String> subscriber) {
                tv.addTextChangedListener(new TextWatcher() {
                    @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
                    @Override public void afterTextChanged(Editable s) { }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        subscriber.onNext(s.toString());
                    }
                });
            }
        });

        return ViewObservable.bindView(tv, textObservable);
}

usernameAvailable receives the mocked data above and looks like this:

    // If the incoming array is size 0 the username is available, otherwise it already exists. 

public Observable<Boolean> usernameAvailable(final String username) {
    return userService.checkUsernameAvailability(username)
            .map(new Func1<List<User>, Boolean>() {
                @Override
                public Boolean call(List<User> usersMatchingUsername) {
                    return usersMatchingUsername.size() == 0;
                }
            });
}

Notice that I am using the 'immediate' scheduler to listen for changes to the EditText. My confusion is this: the unit test always fails, and it seems to me (when I jump into the debugger) that the assertThat statement in the test is firing before the observer ever sees a change in the EditText. I do see in the debugger that the Observer does eventually fire and the text is properly set on the signInButton. I thought using the immediate scheduler would make everything happen as I expect directly after setText is called.

Upvotes: 1

Views: 3878

Answers (2)

vviieett
vviieett

Reputation: 31

Add following before asserting. It works for me.

    // Flush all worker tasks out of queue and force them to execute.
    Robolectric.flushBackgroundThreadScheduler();
    Robolectric.getBackgroundThreadScheduler().idleConstantly(true);

    // A latch used to lock UI Thread.
    final CountDownLatch lock = new CountDownLatch(1);

    try
    {
        lock.await(millisecond, TimeUnit.MILLISECONDS);
    }
    catch (InterruptedException e)
    {
        lock.notifyAll();
    }

    // Flush all UI tasks out of queue and force them to execute.
    Robolectric.flushForegroundThreadScheduler();
    Robolectric.getForegroundThreadScheduler().idleConstantly(true);

Upvotes: 2

WoogieNoogie
WoogieNoogie

Reputation: 1257

I experienced the same issue with Observables. The way I got around is to use

usernameAvailable("username").toBlocking().first();

This will give you the first result of the observable, synchronously in the test.

Upvotes: 1

Related Questions