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

时间:2023-02-17
本文介绍了使用 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 调用的单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:在我的情况下,用户 Mockito 对执行异步任务的函数进行单元测试 下一篇:当我想模拟数据并测试 UI 片段时,doNothing() 不起作用

相关文章

最新文章