如何单元测试改造API调用 [英] How to Unit test Retrofit api calls

查看:163
本文介绍了如何单元测试改造API调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图单元测试用例整合为code可能的每一个块。
但我现在面临的问题,同时添加一些测试用例对于那些经过改装的API调用。

I am trying to integrate Unit test cases for every chunk of code possible. But I am facing issues while adding test cases for api calls that are made through retrofit.

JUnit的编译器永远不会执行的code在回调函数

The JUnit compiler never executes the code in the CallBack functions.

有是使所有的API调用的另一种选择同步作为测试目的,但多数民众赞成不可能在我的应用程序每一个案件。

There is another option of making all the api calls Synchronous for testing purpose, but thats not possible for every case in my app.

任何人都可以请帮我理清了这一点。我要在以任何方式API调用添加测试用例。

Can anyone please help me to sort this out. I have to add test cases in the api calls by any means.

有另一种方法任何建议将是有帮助的。

Any suggestion for another approach will be also helpful.

在此先感谢!

推荐答案

我测试使用的Mockito,Robolectric和Hamcrest库我改造的回调。

I test my Retrofit callbacks using Mockito, Robolectric and Hamcrest libraries.

首先,在你的模块的build.gradle设置lib目录栈:

First of all, set up lib stack in your module's build.gradle:

dependencies {
    testCompile 'org.robolectric:robolectric:3.0'
    testCompile "org.mockito:mockito-core:1.10.19"
    androidTestCompile 'org.hamcrest:hamcrest-library:1.1'
}

在怨妇项目的全球性的build.gradle添加下面一行到buildscript依赖关系:

In jour project's global build.gradle add following line to buildscript dependencies:

classpath 'org.robolectric:robolectric-gradle-plugin:1.0.1'

然后输入构建变种Android Studio中的菜单(快速找到它,按Ctrl + Shift + A和搜索),以及开关测试神器选项为单元测试。 Android的工作室将切换您的测试文件夹com.your.package(测试)(而不是androidTest)。

Then enter "Build Variants" menu in Android Studio (to quickly find it, hit Ctrl+Shift+A and search for it), and switch "Test Artifact" option to "Unit Tests". Android studio will switch your test folder to "com.your.package (test)" (instead of androidTest).

确定。建立完成后,时间写一些测试!

Ok. Set-up is done, time to write some tests!

比方说,你已经有了一些改造API调用来检索需要被放入一个RecyclerView一些适配器等。我们想测试适配器是否被摆满了成功调用适当的项目对象的列表。
要做到这一点,我们需要切换你的改造接口的实现,你使用,使使用模拟电话,并做一些假的反应采取ArgumentCaptor的Mockito类的优势。

Let's say you've got some retrofit api calls to retrieve a list of objects that need to be put into some adapter for a RecyclerView etc. We would like to test whether adapter gets filled with proper items on successful call. To do this, we'll need to switch your Retrofit interface implementation, that you use to make calls with a mock, and do some fake responses taking advantage of Mockito ArgumentCaptor class.

@Config(constants = BuildConfig.class, sdk = 21,
    manifest = "app/src/main/AndroidManifest.xml")
@RunWith(RobolectricGradleTestRunner.class)
public class RetrofitCallTest {

    private MainActivity mainActivity;

    @Mock
    private RetrofitApi mockRetrofitApiImpl;

    @Captor
    private ArgumentCaptor<Callback<List<YourObject>>> callbackArgumentCaptor;

    @Before
    public void setUp() {            
        MockitoAnnotations.initMocks(this);

        ActivityController<MainActivity> controller = Robolectric.buildActivity(MainActivity.class);
        mainActivity = controller.get();

        // then we need to swap the retrofit api impl. with a mock one
        // I usually store my retrofit api impl as a static singleton in class RestClient, hence:
        RestClient.setApi(mockRetrofitApiImpl);

        controller.create();
    }

    @Test
    public void shouldFillAdapter() throws Exception {
        Mockito.verify(mockRetrofitApiImpl)
            .getYourObject(callbackAgrumentCaptor.capture());

        int objectsQuantity = 10;
        List<YourObject> list = new ArrayList<YourObject>;
        for(int i = 0; i < objectsQuantity; ++i) {
            list.add(new YourObject());
        }

        callbackArgumentCaptor.getValue().success(list, null);

        YourAdapter yourAdapter = mainActivity.getAdapter(); // obtain adapter
        // simple test check if adapter has as many items as put into response
        assertThat(yourAdapter.getItemCount(), equalTo(objectsQuantity));
    }

}

右键点击测试类,打运行与测试继续。

Proceed with the test by right clicking the test class and hitting run.

就是这样。我强烈建议使用Robolectric(带robolectric gradle这个插件)和的Mockito,这些库使测试Android应用整个洛塔容易。
我已经学会从以下<一个这种方法href=\"http://www.mdswanson.com/blog/2013/12/16/reliable-android-http-testing-with-retrofit-and-mockito.html\"相对=nofollow>博客文章。另外,请参阅这个答案

And that's it. I strongly suggest using Robolectric (with robolectric gradle plugin) and Mockito, these libs make testing android apps whole lotta easier. I've learned this method from the following blog post. Also, refer to this answer.

这篇关于如何单元测试改造API调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆