Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can test that an OkHttpCall is performed with specific headers?

I have the following class:

class MyClass {
    private OkHttpClient httpClient;
    private String session_id;

    public MyClass() {
        this.setHttpClient(new OkHttpClient());
    }

    public String getSessionId() {
        return session_id;
    }

    public void setHttpClient(OkHttpClient httpClient) {
        this.htttpClient = httpClient;
    }

    public String retrieveUrlContents(String url, String csrfToken) throws Exception {
        url = this.url.replaceAll("/$", "") + "/" + url.replaceAll("^/", "");
        csrfToken = (csrfToken == null) ? "" : csrfToken;

        if (!csrfToken.equals("")) {
            long unixtime = System.currentTimeMillis() / 1000L;
            // AJAX Calls also require to offer the _ with a unix timestamp alongside csrf token
            url += "?_=" + unixtime + "&csrf_token=" + csrfToken;
        }
        Request.Builder request = new Request.Builder()
                .url(url)
                .header("User-Agent", "Mozila/5.0 (X11;Ubuntu; Linux x86_64; rv:87.0) Gecko/20100101 Firefox/87.0");

        String session_id = this.getSessionId();
        session_id = session_id == null ? "" : session_id;

        if (!session_id.equals("")) {
            request.header("Set-Cookie", "session_id=" + session_id + ";login_uid=" + Math.random());
        }

        Response response = this.httpClient.newCall(request.build()).execute();

        int code = response.code();
        if (code != 200) {
            throw new Exception("The url " + url + " returned code " + code);
        }
        String responseBody = response.body().string();
        return responseBody;
    }
}

And I want to unit-test the case that if getSessionId actually return a non-null or a non-empty string then the httpCall is performed:

class MyClassTest {
    private static OkHttpClient mockHttpClient(final String serializedBody, final boolean json, int code) throws IOException {
        final OkHttpClient okHttpClient = mock(OkHttpClient.class);

        final Call remoteCall = mock(Call.class);

        code = code < 0 ? 200 : code;

        final Response response = new Response.Builder()
                .request(new Request.Builder().url("http://url.com").build())
                .protocol(Protocol.HTTP_1_1)
                .code(code).message("").body(
                        ResponseBody.create(
                                MediaType.parse(json ? "application/json" : "text/html"),
                                serializedBody
                        ))
                .build();

        when(remoteCall.execute()).thenReturn(response);
        when(okHttpClient.newCall(any())).thenReturn(remoteCall);

        return okHttpClient;
    }

    @Test
    public void retrieveUrlContentsIsRetrievedWithSessionId() {
        File file = (new File("src/test/resources/csrfInvalid.html")).getAbsoluteFile();
        String path = file.getPath();
        Scanner fileReader = new Scanner(file);
        String contents = fileReader.useDelimiter("\\Z").next();
        OkHttpClient client = this.mockHttpClient(contents, false, 200);

        final Η300sCredentialsRetriever retriever = spy(Η300sCredentialsRetriever.class);
        doReturn("Hello").when(retriever).getSessionId();
        retriever.setUrl("192.168.2.1");
        retriever.setHttpClient(client);

        String response = retriever.retrieveUrlContents("/example.html");

        // Test that http call is permormed with SessionId  
        // Rest of Assertions
    }
}

What I want is to Assert that OkHttp3 is performing an HttpCall with the appropriate Cookie Header. But I do not know how I can assert that the HttpCall is performed with this header. Do you have any ideas how I can test that?

like image 742
Dimitrios Desyllas Avatar asked Dec 13 '25 12:12

Dimitrios Desyllas


1 Answers

One option is MockWebServer, look at RecordedRequest which can confirm the headers you sent.

https://github.com/square/okhttp/tree/master/mockwebserver

https://www.baeldung.com/spring-mocking-webclient#mockwebserverchecking

  RecordedRequest request1 = server.takeRequest();
  assertEquals("/v1/chat/messages/", request1.getPath());
  assertNotNull(request1.getHeader("Authorization"));
like image 89
Yuri Schimke Avatar answered Dec 15 '25 01:12

Yuri Schimke