Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test service calls using mockwebserver that contains redirection?

I am using mockwebserver to mock request and response for my android app. I am testing a login feature which goes through a series of 4 service calls.

  1. Get access token
  2. Re-direct
  3. Get user info (different base url)
  4. Get some other stuff (original base url)

I am trying to mock the response of the redirected call. Here is my code:

@Test
public void testSuccessfulLogin() throws Exception {
    // Post
    server.enqueue(new MockResponse()
            .setResponseCode(HTTP_OK)
            .setBody(getStringFromFile(getInstrumentation().getContext(), "access_token.json")));

    // Redirect
    server.enqueue(new MockResponse().setResponseCode(HTTP_MOVED_TEMP));

    // GET user info
    server.enqueue(new MockResponse().setResponseCode(HTTP_OK).setBody(getStringFromFile(getInstrumentation().getContext(), "userinfo.json")));

    // GET some other stuff
    server.enqueue(new MockResponse().setResponseCode(HTTP_OK)
            .setBody(getStringFromFile(getInstrumentation().getContext(), "sts.json")));

    // Init call
    loginWithoutWaiting(Data.serviceLoginUsername, Data.serviceLoginPassword);

    // Debug (need to loop 4 times to get all 4 call paths)
    RecordedRequest request = server.takeRequest();
    request.getPath();
}

My test fails at the Redirect code. I cannot login. I have found some hints here but I do not fully understand what is going on, thus can't make it work at the moment.

like image 439
AccTest Avatar asked Oct 18 '22 01:10

AccTest


1 Answers

It turned out to be quite easy. In the call that makes redirect, create a new mocked response with response code 302 and header with location url. The next call will use that location url.

case "/userinfo":
return new MockResponse().setResponseCode(HTTP_MOVED_TEMP).setHeader("Location", "/api-test.com/users");

case "/api-test.com/users":
return new MockResponse().setBody("{}")).setResponseCode(HTTP_OK);
like image 92
AccTest Avatar answered Oct 23 '22 09:10

AccTest