与Mockito进行改造2 api呼叫的单元测试

时间:2016-05-20 03:31:40

标签: android unit-testing mockito retrofit2

我需要一些关于如何模拟休息api的建议。我的应用程序是MVP架构。

我的API界面:

public class MyService implements IService {

    private static MyService mInstance = new MyService();
    private MyAPI mApi;

    public static MyService getInstance() {
        return mInstance;
    }

    private MyService() {

        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
        httpClientBuilder.connectTimeout(Config.DEFAULT_TIMEOUT, TimeUnit.SECONDS);

        Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Config.kBaseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .client(httpClientBuilder.build())
            .build();

        this.mApi = retrofit.create(MyAPI.class);
    }

    public void login(
        Subscriber<Response> subscriber,
        String userName,
        String password) {
        mApi.login(Config.kLoginCmd,userName,password)
            .subscribeOn(Schedulers.io())
            .unsubscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(subscriber);
    }

我的服务:

public class LoginPresenter implements LoginContract.Presenter {

    LoginContract.View mView;
    IService mService;
    ISession mSession;

    public LoginPresenter(LoginContract.View loginView, IService service, ISession session) {
        mView = loginView;
        mService = service;
        mSession = session;
    }

    @Override
    public void login(String email, String password) {

        Subscriber<Response> subscriber = new Subscriber<Response>() {
            @Override
            public void onCompleted() {
                mView.showLoading(false);
            }

            @Override
            public void onError(Throwable e) {
                mView.showError(e.getLocalizedMessage());
            }

            @Override
            public void onNext(Response response) {
                if (response.getResults().getStatus().equalsIgnoreCase(Config.kResultCodeOK)) {
                    mView.loginSuccess();
                } else {
                    mView.showError(response.getResults().getStatus().getErrmsg());
                }
            }
        };

        mView.showLoading(true);
        mService.login(
            subscriber,
            email,
            password);
    }

我的演讲者课程:

public class LoginPresenterMockTest {

    private LoginPresenter mLoginPresenter;

    @Mock
    LoginContract.View view;
    @Mock
    IService service;
    @Mock
    ISession session;

    @Before
    public void setup() throws Exception {
        MockitoAnnotations.initMocks(this);
        mLoginPresenter = new LoginPresenter(view, service, session);
    }

    @Test
    public void testLoginWithCorrectUserNameAndPassword() throws Exception {
        mLoginPresenter.login("user@email.com","password");
        verify(view).loginSuccess();
    }

}

还有另一种方法可以通过编写Mock服务来测试我的演示者。但我不喜欢那么多,我认为Mockito可以提供帮助。

这是我的测试类:

form
-----
id

inputs
------
form_id
name

values
-------
input_id
value

我想做的是在响应正确时模拟响应数据调用loginSuccess()。

当然我目前的测试不起作用。我需要一些关于如何嘲笑这个的建议?任何的想法?感谢。

2 个答案:

答案 0 :(得分:5)

您可以通过以下方式完成此操作:

@Test
public void testLoginWithCorrectUserNameAndPassword() throws Exception {
    // create or mock response object
    when(service.login(anyString(), anyString(), anyString).thenReturn(Observable.just(response));
    mLoginPresenter.login("user@email.com","password");
    verify(view).loginSuccess();
}

@Test
public void testLoginWithIncorrectUserNameAndPassword() throws Exception {
    // create or mock response object
    when(service.login(anyString(), anyString(), anyString).thenReturn(Observable.<Response>error(new IOException()));
    mLoginPresenter.login("user@email.com","password");
    verify(view).showError(anyString);
}

答案 1 :(得分:4)

感谢 @Ilya Tretyakov ,我推出了这个解决方案:

private ArgumentCaptor<Subscriber<Response>> subscriberArgumentCaptor;

@Test
public void testLoginWithCorrectUserNameAndPassword() throws Exception {
    mLoginPresenter.login("user@email.com","password");
    // create the mock Response object
    Response response = ......

    verify(service, times(1)).login(
        subscriberArgumentCaptor.capture(),
        stringUserNameCaptor.capture(),
        stringPasswordCaptor.capture()
    );

    subscriberArgumentCaptor.getValue().onNext(response);
    verify(view).loginSuccess();
}