DEV Community

Dimitrios Desyllas
Dimitrios Desyllas

Posted on

How I can test that an OkHttpClient performs an HttpCall with the appropriate Cookie Header?

As I ask upon I want to know how I can test that an Class that has an OkHttpClient Instance as its private instance variable performs an Http request with the appropriate cookie value.

The method that I want to test is the:

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

            long unixtime = System.currentTimeMillis() / 1000L;
            // AJAX Calls also require to offer the _ with a unix timestamp alongside csrf token
        Request.Builder request = new Request.Builder()
                .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;


        Response response = this.httpClient.newCall(;

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

And my test is (in incomplete form):

    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);

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

        // Test that http call is permormed with SessionId  
        // Rest of Assertions
Enter fullscreen mode Exit fullscreen mode

More Info in my SO question. Can you help me with my test?

Top comments (0)