单元测试一个使用httpclient的类

时间:2017-07-10 09:40:57

标签: java unit-testing junit mockito

我想为这个使用HttpURLConnection的类编写单元测试用例。到目前为止,我还没有使用任何模拟框架,因此很难确定方法。

public class DemoRestClient implements Closeable {

    private final String instanceId;
    private final String requestId;
    private HttpURLConnection conn;

    public DemoRestClient(String instance, String reqId, String url) {
        this.instanceId = instance;
        this.requestId = reqId;

        try {
            URL urlRequest = new URL(url);
            conn = (HttpURLConnection) urlRequest.openConnection();
        } catch (IOException iox) {
            throw new RuntimeException("Failed to connect", iox);
        }
    }

    public InputStream run() {

        try {
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("Accept-Encoding", "gzip");

            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
            }

            return new GZIPInputStream(conn.getInputStream());
        } catch (IOException iox) {
            throw new RuntimeException("Data fetching failed!", iox);
        }
    }

    @Override
    public void close() throws IOException {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

如果你经历过这种情况,请遮挡一些光线。谢谢!

2 个答案:

答案 0 :(得分:2)

您必须在建设时提供HttpURLConnection或让DemoRestClient委托工厂(或类似人员)创建HttpURLConnection

例如:

public DemoRestClient(String instance, String reqId, HttpURLConnection connection) {
    ...
    this.conn = connection;
}

或者

public DemoRestClient(String instance, String reqId, ConnectionFactory connectionFactory) {
    ...
    this.conn = connectionFactory.create();
}

使用这些方法中的任何一种,您将控制HttpURLConnection中正在使用的实际DemoRestService实例,然后您可以开始模拟它以支持您所需的测试行为。

例如:

@Test
public void someTest() throws IOException {
    HttpURLConnection connection = Mockito.mock(HttpURLConnection.class);
    String instance = "...";
    String reqId = "...";

    DemoRestClient demoRestClient = new DemoRestClient(instance, reqId, connection);

    // in case you need to mock a response from the conneciton
    Mockito.when(connection.getInputStream()).thenReturn(...);

    demoRestClient.run();

    // in case you want to verify invocations on the connection
    Mockito.verify(connection).setRequestMethod("GET");
}

答案 1 :(得分:2)

您可以从HttpURLConnection类中提取DemoRestClient对象的创建,并通过构造函数注入构造的实例。

这将允许您创建一个HttpURLConnection类型的模拟,您可以在单元测试中使用它来验证DemoRestClient是否与您期望的HttpURLConnection模拟交互到。