简体   繁体   中英

How to write tests on HTTP client apache?

I am trying to write a test for my service that sets up a connection with another service that returns me items from the database. My problem is that I set the connection properties in the test and start the service. How can this be mock or something similar?

My start service method:

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();
    }

My setup test method and one test method:

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
    }

How to do it correctly, so as not to configure the connection in the tests?

Javalin would be an excellent tool for mocking the real service as it allows for state assertions in your tests.

Wiremock can be used as well. But it leads to hard to maintain behavioral tests (verify).

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