Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking okhttp response

I have the below method which executes a GET request 3 times until its successfully.

What would be the better way to mock this method? I want to mock and test status_code 401, status code 500 and want to test if the method is executed thrice.

In python, we have https://github.com/getsentry/responses which mocks the requests directly, so its easy to test these methods.

Is there anything equivalent in Java.

@Override
    public <T> UResponse<T> get(Request request, JSONUnmarshaler<T> unmarshaller, Gson gson) throws UException {
        int status_code = 0;
        String next = null;
        String rawJSON = null;
        JsonElement jsonelement = null;
        Boolean retry = true;
        try {
            int attempts = 3;
            while ((attempts >= 0)  && (retry) && status_code != 200){
                Response response = this.client.newCall(request).execute();

                rawJSON = response.body().string();

                jsonelement = gson.fromJson(rawJSON, JsonElement.class);

                next = gson.fromJson(jsonelement.getAsJsonObject().get("next"), String.class);

                status_code = response.code();

                if (status_code == 401) {
                    try {
                        logger.warn("token expired");
                        TimeUnit.SECONDS.sleep(5);
                        retry = true;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                if ((status_code / 100 ) == 5){
                    logger.warn("gateway error");
                    retry = true;                   
                }
                attempts -= 1;
                retry = false;

            }
            if (status_code != 200){
                throw new UException();
            }
            return new UResponse<T>(status_code, next, rawJSON,
                    unmarshaller.fromJSON(gson, jsonelement.getAsJsonObject()));

        } catch (IOException e) {
            e.printStackTrace();
            throw new UException();

        }
like image 723
user1050619 Avatar asked Jan 29 '19 02:01

user1050619


People also ask

What is OkHttp in Java?

OkHttp is an efficient HTTP & HTTP/2 client for Android and Java applications. It comes with advanced features, such as connection pooling (if HTTP/2 isn't available), transparent GZIP compression, and response caching, to avoid the network completely for repeated requests.


1 Answers

This would be hard to test because it loops. One solution would be to break out this.client.newCall(request).execute() into a separate function sendRequest(Request request, int attemptsRemaining). Then you could use a spy that stubs that method to return different responses depending on the number of attempts remaining.
The nice thing I realized about okhttp is that you can just build a fake response yourself. For example,

Request mockRequest = new Request.Builder()
                .url("https://some-url.com")
                .build();
return new Response.Builder()
                .request(mockRequest)
                .protocol(Protocol.HTTP_2)
                .code(401) // status code
                .message("")
                .body(ResponseBody.create(
                        MediaType.get("application/json; charset=utf-8"),
                        "{}"
                ))
                .build();

So you can create and stub a simple method that returns a response, and you're basically good to go for testing.

like image 176
Andrew Puglionesi Avatar answered Sep 18 '22 16:09

Andrew Puglionesi