我正在使用 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
被调用后直接发生。