3

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?

shadox
  • 3,238
  • 4
  • 24
  • 38

1 Answers1

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.

Egor
  • 39,695
  • 10
  • 113
  • 130