【发布时间】:2021-08-31 01:47:24
【问题描述】:
这是我第一次尝试使用 spring 框架测试编写集成测试。控制器在 Postman 中返回正确的响应,但 MvcResult 返回“application/json;charset=UTF-8”作为响应。我尝试了互联网上存在的不同解决方案,但似乎没有任何效果。请帮帮我。
我想从 JSON 响应中提取键值对。
春季测试 = 5.1.8.RELEASE
控制器
@RestController
public class CustAuController {
@RequestMapping(value = "/retrieve_something", method = RequestMethod.GET)
retrieveSomething(){
}
}
邮递员回复
{
"total_count" : 3,
"data" : {
"list" : [
{
...
}
]
}
}
测试类
@SpringBootApplication
@SpringBootTest(classes = ServiceApplication.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class ControllerTest {
@Autowired
WebApplicationContext webApplicationContext;
MockMvc mockMvc;
public static String asJsonString(final Object obj) {
try {
final ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@BeforeAll
void setMockMvc() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
@DisplayName("Retrieve Something")
@Order(1)
void testRetrieveSomething() throws Exception{
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get(
"/retrieve_something"))
.andExpect(status().isOk()).andReturn();
System.out.println(
result.getResponse().getContentType()); // returns application/json;charset=UTF-8
}
}
【问题讨论】:
标签: java spring-boot integration-testing junit5 spring-boot-test