1

我正在使用 Robolectric 3.0 快照。

我有一个测试:

@Test
public void my_test() throws Exception {
        when(testReferenceManager.getUserServiceMock().checkUsernameAvailability(anyString())).thenReturn(Observable.just(Arrays.asList(new User("test@email.com", "password"))));
        when(testReferenceManager.getUserServiceMock().checkAuthStatus(anyString())).thenReturn(Observable.just(Arrays.asList(new User("test@email.com", "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("test@email.com");
        passwordText.setText("password");

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

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

这里的关键是,如果 API 报告用户存在(它从上面的模拟中执行),则登录按钮文本应该与名为的字符串资源的值相同R.string.button_login

更改按钮状态的设置在我的 Activity 中完成,如下所示:

        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 只是以反应方式包装了 textChangedListener 接口:

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 接收上面的模拟数据,如下所示:

    // 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;
                }
            });
}

请注意,我正在使用“立即”调度程序来监听 EditText 的更改。我的困惑是:单元测试总是失败,在我看来(当我跳入调试器时)assertThat测试中的语句在观察者看到 EditText 的变化之前就被触发了。我确实在调试器中看到 Observer 最终会触发,并且在 signInButton 上正确设置了文本。我认为使用即时调度程序会让一切都像我期望的那样在setText被调用后直接发生。

4

2 回答 2

2

在断言之前添加以下内容。这个对我有用。

    // 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);
于 2015-08-21T09:04:00.870 回答
1

我在使用 Observables 时遇到了同样的问题。我解决的方法是使用

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

这将为您提供可观察的第一个结果,在测试中同步。

于 2015-02-15T04:01:21.310 回答