OkHttp implement unit test?

Viewed 126

I have a function using OkHttp to get data from third party api

    public List<AuditData> getAuditData(OkHttpClient client, int retLabelId, int countryId, int periodId, int versionNo, String URL, String token) throws IOException {
        DefaultGraphQLClient graphQLClient = new DefaultGraphQLClient(URL);
        String query = QueryUtils.getAuditDataQuery(retLabelId, countryId, periodId, versionNo, PartitionUtil.getReadPartition(token));
        GraphQLResponse response = graphQLClient.executeQuery(query, new HashMap<>(), "", (url, headers, body) -> {
                Request request = new Request.Builder()
                    .header("Authorization", "Bearer " + token)
                    .url(url)
                    .post(RequestBody.create(okhttp3.MediaType.parse("text/x-markdown"), body))
                    .build();
                try {
                    Response responseOkHttp = client.newCall(request).execute();
                    return new HttpResponse(responseOkHttp.code(), responseOkHttp.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
        );
        return response.extractValueAsObject("data.auditData[*]", new TypeRef<List<AuditData>>() {
        });
    }

I want to write unit test for the function above. I have tried with MockWebServer and it doesn't work.

        MockResponse response = new MockResponse()
            .addHeader("Content-Type", "application/json; charset=utf-8")
            .addHeader("Cache-Control", "no-cache")
            .setBody(jsonResponse);

        server.enqueue(response);

        OkHttpClient client = new OkHttpClient();
0 Answers
Related