【发布时间】:2017-03-29 12:06:43
【问题描述】:
我的应用程序中有 MVP。 Presenter有接口
public interface ILoginPresenter<V> extends Presenter<V> {
void logUserIn(String email, String password, String deviceToken, String deviceType);
}
实现有RX Single
mLoginSubscription = mModel.logUserIn(email, password, deviceToken, deviceType)
.compose(RxUtil.setupNetworkSingle())
.subscribe(new Subscriber<User>() {
@Override
public void onCompleted() {
Timber.i("Log in complete");
}
@Override
public void onError(Throwable e) {
Timber.e(e, "Retrofit could not get User.");
getView().dismissProgressDialog();
}
@Override
public void onNext(UserResponseRetrofit response) {
Timber.i("Retrofit is attempting to get User");
mSaveModel.saveUser(user);
getView().dismissProgressDialog();
getView().goToMenuActivity();
}
});
我还有 Dagger 的模块
@Module
public class ModelModule {
@Provides
@ScreenScope
public ILoginModel provideLoginModel(LoginModel p) {
return p;
}
}
我的单元测试如下所示:
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21, manifest = "/src/main/AndroidManifest.xml")
public class LoginPresenterTest {
public static final String SOME_OTHER_TOKEN = "someOtherToken";
private AppComponent mAppComponent;
private LoginComponent mLoginComponent;
private ILoginView mockView;
private ModelModule mockModel;
private ILoginPresenter mLoginPresenter;
@Before
public void setup() {
// Creating the mocks
mockView = Mockito.mock(ILoginView.class);
mockModel = Mockito.mock(ModelModule.class);
ILoginModel mock = Mockito.mock(ILoginModel.class);
User urr = Mockito.mock(User.class);
Mockito.when(mockModel.provideLoginModel(null)).thenReturn(mock);
Mockito.when(mock.logUserIn("", "", "", "")).thenReturn(ScalarSynchronousSingle.just(urr));
mAppComponent = DaggerAppComponent.builder()
.appModule(new AppModule(RuntimeEnvironment.application))
.build();
mLoginComponent = DaggerLoginComponent.builder()
.appComponent(mAppComponent)
.modelModule(mockModel)
.presenterModule(new PresenterModule())
.build();
mLoginPresenter = mLoginComponent.provideLoginPresenter();
mLoginPresenter.setView(mockView);
}
@Test
public void testLogin() {
mLoginPresenter.logUserIn("", "", "", "");
try {
java.lang.Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Mockito.verify(mockView).dismissProgressDialog();
}
所以使用 Dagger 我需要正确构建 Presenter。为此,我正在尝试使用 Mockito.when。首先看起来这条线不起作用
Mockito.when(mockModel.provideLoginModel(null)).thenReturn(mock);
目标是使用我自己的Model实现,返回Single。
真的不明白为什么我的 ModelModule 模拟不起作用?
【问题讨论】:
-
不起作用是什么意思?你的意思是它没有返回你的模拟?你确定 dagger 用参数
null调用provideLoginModel吗?如果您不关心参数,请执行Mockito.when(mockModel.provideLoginModel(any())).thenReturn(mock); -
谢谢
any()- 是我其他几个问题的答案 -
太好了,我更新了答案以帮助未来的读者。
标签: android unit-testing mockito dagger-2