How can I test gzip with mockMvc?
Asked Answered
C

0

8

I'm testing spring boot compression property:

server.compression.enabled=true

I would like to validate that after sending a request with a header "Accept-Encoding":"gzip",
I would receive a response with header "Content-Encoding":"gzip".

The test is working with TestRestTemplate, but it doesn't work with MockMvc.

I created a new project and added the above property, and also this controller:

@RestController
public class IssueController {

    @GetMapping
    public Person getString() {
        return new Person("ADSDSADSDSA", "REWREWREWREW");
    }

    class Person {
        private String name;
        private String surname;

        //Constructor, getters and setters
    }
}

Working test with TestRestTemplate

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TestIssueControllerIntegrationTest {

    @Autowired
    private TestRestTemplate testRestTemplate;

    @Test
    public void testGzip(){
        HttpHeaders httpHeaders= new HttpHeaders();
        httpHeaders.add("Accept-Encoding", "gzip");

        HttpEntity<Void> requestEntity = new HttpEntity<>(httpHeaders);

        ResponseEntity<byte[]> response = testRestTemplate.exchange("/", HttpMethod.GET, requestEntity, byte[].class);

        assertThat(response.getHeaders().get("Content-Encoding").get(0), equalTo("gzip"));
    }
}

Test not working with MockMvc

@WebMvcTest(IssueController.class)
public class TestIssueController {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testGzip() throws Exception {
        MvcResult result = this.mockMvc.perform(MockMvcRequestBuilders.get("/").header("Accept-Encoding", "gzip")).andReturn();

        assertThat(result.getResponse().getHeader("Content-Encoding"), CoreMatchers.equalTo("gzip"));
    }
}

Is it really impossible to test the compression with mockMvc or I'm doing something wrong ?

Thank you in advance

Crowe answered 20/1, 2022 at 15:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.