如何在HTTP客户端Apache上编写测试?

时间:2019-02-22 09:11:25

标签: java unit-testing junit mocking mockito

我正在尝试为我的服务编写测试,以建立与另一个服务的连接,该服务从数据库返回我的项目。我的问题是我在测试中设置了连接属性并启动了服务。这怎么可能是假的或类似的东西?

我的启动服务方法:

public void doStartService() {
        super.doStartService();
        PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager();
        manager.setDefaultMaxPerRoute(maxConnectionsPerRoute);
        manager.setMaxTotal(maxConnections);

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(connectTimeout)
                .setSocketTimeout(socketTimeout)
                .setRedirectsEnabled(false).build();

        HttpClientBuilder builder = HttpClientBuilder.create();
        builder.setDefaultRequestConfig(requestConfig);
        builder.setConnectionManager(manager);
        client = builder.build();
    }

我的设置测试方法和一种测试方法:

private ProductCatalogIntegrationService service;

 @Before
    public void setup() {
        service = new Service();
        service.setConnectTimeout(10000);
        service.setSocketTimeout(10000);
        service.setMaxConnections(10);
        service.setMaxConnectionsPerRoute(10);
        service.setUrl("http://localhost:8888/products");
        service.doStartService();
    }


    @Test
    public void testReturnProductById() {
        service.setProductById(GET_PRODUCT_BY_ID); // set url from get product by id, by this url my other service goes to the database
        jsonItem = service.getProductById("1"); //get product by id 1

        assertEquals(jsonItem.getId(), FIRST_PRODUCT_ID); // I compare the id on which I made the request to the database, so that I came and was wrapped in a class wrapper
    }

如何正确执行操作,以免在测试中配置连接?

1 个答案:

答案 0 :(得分:2)

Javalin将是模拟真实服务的绝佳工具,因为它允许在测试中声明状态。

Wiremock也可以使用。但这会导致难以维持行为测试(验证)。