简体   繁体   中英

Inject HttpClient to get mock response in Java using GUICE

I am new to guice and injections. Need a help in writing the unit test.

I have a method that fetches a session token by making a GET request

String strTemp = "";
        String sessionToken = "" ;
        HttpResponse response;
try { String url = String.format(URL_SESSION, email); HttpGet request = new HttpGet(url); <b>response = client.execute(request);</b> } catch (Throwable e) { LOG.error("Could not reach to the Server"); throw new ExecutionException(e, "Could not reach to the Server") .withReason(Throwables.getRootCause(e).getMessage()) .withResolution("Check if the outbound Port is open and you can reach the Rapportive service"); }

In my unit test I wanna Inject the HttpClient to get a mock response. I have written a Mock Class

public abstract class MockHttpRequestBadQuery implements HttpClient {

    protected HttpResponse execute(HttpGet httpUriRequest) throws IOException {
        HttpResponse httpResponse = new BasicHttpResponse(new StatusLine() {
            @Override
            public ProtocolVersion getProtocolVersion() {
                return new ProtocolVersion("HTTP/1.1", 0, 0);
            }

            @Override
            public int getStatusCode() {
                return 400;
            }

            @Override
            public String getReasonPhrase() {
                return "Bad Request";
            }
        });
        HttpEntity entity = new StringEntity("{\"message\":\"\\n" +
                "SELECT badFieldName FROM Account\\n" +
                "       ^\\n" +
                "ERROR at Row:1:Column:8\\n" +
                "No such column \'badFieldName\' on entity \'Account\'. If you are attempting to use" +
                " a custom field, be sure to append the \'__c\' after the custom field name. Please" +
                " reference your WSDL or the describe call for the appropriate names.\"," +
                " \"errorCode\":\"INVALID_FIELD\"}");
        httpResponse.setEntity(entity);
        httpResponse.setHeader("Content-Type", "application/json;charset=UTF-8");
        httpResponse.setHeader("Date", "Tue, 28 May 2013 16:06:21 GMT");
        httpResponse.setHeader("Transfer-Encoding", "chunked");
        return httpResponse;
    }
}

I need help in how to inject so that whenever client.execute() is called, a mock response is generated.

It's not clear from the code you posted how the real HttpClient dependency is added to the real class. But here is the way you can do it for both real and test scenarios:

public class RealClassThatNeedsClientDep {

    @Inject private HttpClient client;

    public method useClient() {
        client.doStuff(); // client was injected at instance creation by Guice
    }

    public static void main(String[] args) {
        Injector injector = Guice.createInjector(new RealModule());
        injector.getInstance(RealClassThatNeedsClientDep.class).useClient();
    }
}

The class has a client as an injected instance variable. If there is a default no-args constructor for that client class, then that is all you need to do. If there is not, or if you want to apply custom logic to the client being injected there, then in your RealModule you can use a provider to bind the client. Note I don't know what kind of HttpClient you're using, so the methods below are most likely fake.

public class RealModule {
    /** provider only needed if HttpClient has no default no-args public constructor */
    @Provides HttpClient getClient() {
        return HttpClient.getNewInstance().customize();
    }
}

In your test module you can bind a mock client for injection instead, and install the test module into the test class.

public class TestModule {

    @Provides HttpClient getClient() {
        // define mock client using Mockito or roll your own
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM