Android Local Tests vs Instrumented Test

佐手、 提交于 2019-12-23 20:06:16

问题


I'm trying to check if my API is available within a unit test, to be sure that it responds with 200.

Now, my problem is that I'm not really sure when to use Local Test and when I have to use Android Instrumentation Tests. I know that I have to use Instrumented Tests for UI testing but how to test the endpoint?

I use Retrofit2 for communication. And tried to test Endpoint in 2 ways with Local Tests.

Example 1 (synchronous, does not work)

public class EndpointTest {

    EndpointApi api;
    SimpleInjection simpleInjection;

    @Before
    public void setUp() {
        simpleInjection = new SimpleInjection();
        api = simpleInjection.getEndpointApi();
    }

    @Test
    public void endpoint_1_isAvailable() {
        Call<ApiResponse> rootCall = api.getRoot();
        try {
            int reponseCode = rootCall.execute().code();
            Assert.assertEquals(200, reponseCode);

        } catch (IOException e) {
            Assert.fail();
        }
    }         
}

Example 2 (asynchronous, does work)

public class EndpointTest {

    EndpointApi api;
    SimpleInjection simpleInjection;

    @Before
    public void setUp() {
        simpleInjection = new SimpleInjection();
        api = simpleInjection.getEndpointApi();
    }

    @Test
    public void endpoint_2_isAvailable() {
    Call<ApiResponse> rootCall = api.getRoot();

        rootCall.enqueue(new Callback<ApiResponse>() {
            @Override
            public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
                Assert.assertEquals(200, response.code());
            }

            @Override
            public void onFailure(Call<ApiResponse> call, Throwable t) {
                Assert.fail();
            }
        });
    }         
}

Do I have to use Android Instrumentation Test for asynchronous mode?


回答1:


The decision of whether to run your tests on a local JVM on your development machine or on an Android device/emulator is not based on whether your code is synchronous or not. Usually you would only want to run unit tests locally, as it's a lot faster and allows you to use TDD. Your tests do network requests, so they're not unit tests per say, since they have the dependency on the server - they are integration tests. It's preferable to run integration tests on an Android device to get better feedback.



来源:https://stackoverflow.com/questions/35777394/android-local-tests-vs-instrumented-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!