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 https://stackoverflow.com/q/67045916/4706711 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;

        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;
    }
Enter fullscreen mode Exit fullscreen mode

And my test is (in incomplete form):

 @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
    }
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)