我正在尝试重构一个相当老的项目,所以我开始用Dagger2,RxJava,RxAndroid实现新的体系结构(MVVM)...现在一切都已连接并且工作正常,现在的问题是,我不知道如何为我的ViewModel编写单元测试。
我想首先从“登录”屏幕开始,所以我创建了一个LoginViewModel,但首先让我向您展示我的工作。
我有一个提供2个类的DataModule,分别是RestApiRepository和ViewModelFactory。 RestApiRepository看起来像这样:
public class RestApiRepository {
private RestClient restClient;
public RestApiRepository(RestClient restClient) {
this.restClient = restClient;
}
public Observable<AuthResponseEntity> authenticate(String header, AuthRequestEntity requestEntity) {
return restClient.postAuthObservable(header, requestEntity);
}
}
带有api调用的其他客户端登录:
public interface RestClient {
@POST(AUTH_URL)
Observable<AuthResponseEntity> postAuthObservable(@Header("Authorization") String authKey, @Body AuthRequestEntity requestEntity);
}
DataModule的第二个类是ViewModelFactory:
@Singleton
public class ViewModelFactory extends ViewModelProvider.NewInstanceFactory implements ViewModelProvider.Factory {
private RestApiRepository repository;
@Inject
public ViewModelFactory(RestApiRepository repository) {
this.repository = repository;
}
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
if (modelClass.isAssignableFrom(LoginViewModel.class)) {
return (T) new LoginViewModel(repository);
}
throw new IllegalArgumentException("Unknown class name");
}
}
最后,LoginViewModel:
public class LoginViewModel extends ViewModel {
private final CompositeDisposable disposable = new CompositeDisposable();
private final MutableLiveData<AuthResponseEntity> responseLiveData = new MutableLiveData<>();
private RestApiRepository restApiRepository;
private SchedulerProvider provider;
public LoginViewModel(RestApiRepository restApiRepository, SchedulerProvider provider) {
this.restApiRepository = restApiRepository;
this.provider = provider;
}
public MutableLiveData<AuthResponseEntity> getResponseLiveData() {
return responseLiveData;
}
@Override
protected void onCleared() {
disposable.clear();
}
public void auth(String token, AuthRequestEntity requestEntity) {
if (token != null && requestEntity != null) {
disposable.add(restApiRepository.authenticate(token, requestEntity)
.subscribeOn(provider.io())
.observeOn(provider.ui())
.subscribeWith(new DisposableObserver<AuthResponseEntity>() {
@Override
public void onNext(AuthResponseEntity authResponseEntity) {
responseLiveData.setValue(authResponseEntity);
}
@Override
public void onError(Throwable e) {
AuthResponseEntity authResponseEntity = new AuthResponseEntity();
authResponseEntity.setErrorMessage(e.getMessage());
responseLiveData.setValue(authResponseEntity);
}
@Override
public void onComplete() {
}
}
));
}
}
}
所以,我确定一切都连接良好,我可以成功登录...
对于RxAndroid测试问题,我发现我必须像这样使用Scheduler提供程序:
public class AppSchedulerProvider implements SchedulerProvider {
public AppSchedulerProvider() {
}
@Override
public Scheduler computation() {
return Schedulers.trampoline();
}
@Override
public Scheduler io() {
return Schedulers.trampoline();
}
@Override
public Scheduler ui() {
return Schedulers.trampoline();
}
}
下面是我的LoginViewModelTest类,但我不知道如何在测试中处理RxJava / RxAndroid。
@RunWith(MockitoJUnitRunner.class)
public class LoginViewModelTest {
@Mock
private RestApiRepository restApiRepository;
@Mock
private MutableLiveData<AuthResponseEntity> mutableLiveData;
private LoginViewModel loginViewModel;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
AppSchedulerProvider schedulerProvider = new AppSchedulerProvider();
loginViewModel = Mockito.spy(new LoginViewModel(restApiRepository, schedulerProvider));
}
@Test
public void authenticate_error() {
String token = "token";
AuthRequestEntity requestEntity = Mockito.mock(AuthRequestEntity.class);
Mockito.doReturn(Observable.error(new Throwable())).when(restApiRepository).authenticate(token, requestEntity);
loginViewModel.auth(token, requestEntity);
AuthResponseEntity responseEntity = Mockito.mock(AuthResponseEntity.class);
responseEntity.setErrorMessage("Error");
Mockito.verify(mutableLiveData).setValue(responseEntity);
}
}
所以,我想在调用onError时编写一个针对失败情况的测试,但是当我运行它时,却出现此错误:
exclude patterns:io.reactivex.exceptions.UndeliverableException: The exception could not be delivered to the consumer because it has already canceled/disposed the flow or the exception has nowhere to go to begin with. Further reading: https://github.com/ReactiveX/RxJava/wiki/What's-different-in-2.0#error-handling | java.lang.RuntimeException: Method getMainLooper in android.os.Looper not mocked. See http://g.co/androidstudio/not-mocked for details.
答案 0 :(得分:0)
您可以嘲笑restApiRepository
的行为:
Mockito.when(restApiRepository.authenticate(token, requestEntity)).thenReturn(Observable.error(error));
并确认正在使用适当的参数调用responseLiveData.setValue