要比较ResponseEntities Spring测试的MockMVC,可以使用以下步骤:
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class MyControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testGetEntity() throws Exception {
mockMvc.perform(get("/entity"))
.andExpect(status().isOk())
.andReturn();
}
}
@RestController
public class MyController {
@GetMapping("/entity")
public ResponseEntity getEntity() {
String body = "Hello World";
HttpHeaders headers = new HttpHeaders();
headers.add("Custom-Header", "Value");
return new ResponseEntity<>(body, headers, HttpStatus.OK);
}
}
这个示例中,我们使用MockMvc的perform方法发送一个GET请求到"/entity"路径,并使用andExpect方法验证返回的状态码是否是200。你还可以进一步验证响应的内容、头信息等。
这样,你就可以比较ResponseEntities Spring测试的MockMVC了。