Eva*_*dro 8 java spring-mvc spring-boot mockmvc
我正在测试 Spring Boot 压缩属性:
server.compression.enabled=true
我想验证在发送带有 header 的请求后"Accept-Encoding":"gzip",
我会收到带有 header 的响应"Content-Encoding":"gzip"。
该测试适用于 TestRestTemplate,但不适用于 MockMvc。
我创建了一个新项目并添加了上述属性以及此控制器:
@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
}
}
Run Code Online (Sandbox Code Playgroud)
使用 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"));
}
}
Run Code Online (Sandbox Code Playgroud)
测试不适用于 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"));
}
}
Run Code Online (Sandbox Code Playgroud)
真的不可能用mockMvc测试压缩还是我做错了什么?
先感谢您