使用 Mockito 进行 Retrofit 2 api 调用的单元测试

Unit Test of Retrofit 2 api call with Mockito(使用 Mockito 进行 Retrofit 2 api 调用的单元测试)
本文介绍了使用 Mockito 进行 Retrofit 2 api 调用的单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我需要一些关于如何模拟 rest api 的建议.我的应用程序采用 MVP 架构.

I need some advices on how to mock a rest api. My application is in MVP architecture.

我的 API 接口:

public interface MyAPI {

    @GET("{cmd}/{userName}/{password}")
    Observable<Response> login(
        @Path("cmd") String cmd,
        @Path("userName") String userName,
        @Path("password") String password
    );

我的服务:

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

还有另一种方法可以通过编写模拟服务来测试我的演示者.但我不太喜欢这样,我认为 Mockito 可以提供帮助.

There is another way to test my presenter by writing a Mock service. But I don't like that so much and I think Mockito could help.

这是我的测试类:

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

}

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

What I want to do is I mock the response data call loginSuccess() when the response is correct.

当然,我目前的测试不会奏效.我需要一些关于如何模拟这个的建议?任何的想法?谢谢.

Of course my current test will not work. I need some advices on how to mock this? Any idea? Thanks.

推荐答案

你可以用下一个方法:

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

这篇关于使用 Mockito 进行 Retrofit 2 api 调用的单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Android Mocking a Dagger2 injected dependency for a Espresso test(Android 为 Espresso 测试模拟 Dagger2 注入依赖项)
Mock object in Android Unit test with kotlin - any() gives null(使用 kotlin 在 Android 单元测试中模拟对象 - any() 给出 null)
How to mock Context using Mockito?(如何使用 Mockito 模拟上下文?)
Unit test Android, getString from resource(单元测试Android,从资源中获取字符串)
Mockito - what does verify method do?(Mockito - 验证方法有什么作用?)
Unit Testing in Retrofit for Callback(回调改造中的单元测试)