'How to make multiple API calls, so next one won't overwrite previous one cookies

I want to automate shopping and I have one method to add a product to a cart:

    public Response addToCart(@NotNull Product product, int quantity) {
        Header header = new Header("content-type", "application/x-www-form-urlencoded");
        Headers headers = new Headers(header);

        HashMap<String, String> formData = new HashMap<>();
        formData.put("product_sku", "");
        formData.put("product_id", String.valueOf(product.getId()));
        formData.put("quantity", String.valueOf(quantity));

        if (cookies == null) {
            cookies = new Cookies();
        }

        Response response = post(Endpoint.ADD_TO_CART.url, cookies, headers, formData);

        if (response.getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed to add the product" + product.getId() + " to the cart, HTTP status code: " +
                            response.getStatusCode());
        }

        this.cookies = response.getDetailedCookies();
        return response;
    }

And here is my test method, that reads products from json file and adds item to a cart

    public void addAllProductsToCart() throws IOException {
        Product[] products = JacksonUtils.deserializeJSON("products.json", Product[].class);
        CartApi cartApi = new CartApi();
        HomePage homePage = new HomePage(getDriver());
        homePage.load();
        Arrays.stream(products).forEach(product -> {
            cartApi.addToCart(product, 1);
            injectCookiesToBrowser(cartApi.getCookies());
        });
        CartPage cartPage = new CartPage(getDriver());
        cartPage.load();
        final int uniqueItemsInCart = cartPage
                .load()
                .countUniqueItems();
        Assert.assertEquals(uniqueItemsInCart, products.length);
    }

This is injectCookiesToBrowser method if anyone wondered:

    protected void injectCookiesToBrowser(Cookies cookies) {
        List<Cookie> seleniumCookieList = CookieUtils.convertRestAssuredCookiesToSeleniumCookies(cookies);
        for (Cookie cookie : seleniumCookieList) {
            getDriver()
                    .manage()
                    .addCookie(cookie);
        }
    }

The problem is, only the last product from my json file gets added to a cart. There are 13 unique items, but it seems that each purchase overwrites previous one (assertion says 1 instead of 13). Can anyone help?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source