Search code examples
javahtmlunit

HtmlUnit, how to check if every asset was loaded?


I am using HtmlUnit for integration-testing.

In HtmlUnit, there is WebResponse::getStatusCode() for accessing HTTP_STATUS_CODE of currently loaded page. Let's say, my Page is "about" google.com, statusCode will be 200, usually.

I am wondering, if it is possible with HtmlUnit to check, if all required assets (*.css, *.js) were loaded successfully (200 <= statusCode < [300|400]).

In my use case, my tested page works fine - but a .css-file is missing, so the layout is broken. I would like to assert in my test-case, that each required assert can be loaded.


Solution

  • You can intercept all communication and store information about all assets.

    Something like:

    new WebConnectionWrapper(webClient) {
    
        public WebResponse getResponse(WebRequest request) throws IOException {
            WebResponse response = super.getResponse(request);
    
            URL url = request.getUrl();
            int status = response.getStatusCode();
            // store the status
    
            return response;
        }
    };