gpt4 book ai didi

spring - spring mvc测试中访问请求体和请求头

转载 作者:行者123 更新时间:2023-12-02 05:25:20 26 4
gpt4 key购买 nike

我创建了一个 Spring Boot 应用程序,这就是我的 Controller 的样子。我使用 postman 发送请求正文中的 json 和请求 header 中的字符串,然后进一步散列 json 并将其与请求 header 获取的字符串进行比较。问题是我不知道如何获取请求正文和请求 header ,以便使用 MockMvc 测试相应的 Controller 类。

Controller 逻辑

@RestController
public class Comparison {

@PostMapping(path = "/test")
public boolean compareHash(@RequestBody String json,
@RequestHeader(value = "code") String oldHashValue) {

Hash hashObj = new Hash();
String newHashValue = hashObj.sha512(json);
return oldHashValue.equals(newHashValue);
}
}

测试逻辑

public class ComparisionTest {

@Autowired
private WebApplicationContext wac;

private MockMvc mockMvc;

@Before
public void setup () {
DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac);
this.mockMvc = builder.build();
}

@Test
public void contextLoads() throws Exception {
RecordedRequest recordedRequest = server.takeRequest();
}
}

请帮助我在上面的代码中检索请求的正文和 header 值,并将哈希(正文)与 header 值等同

最佳答案

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ApplicationTest {

@Autowired
private MockMvc mockMvc;

@Test
public void test() {

mockMvc.perform(post("<<url>>").content("<<jsonStrig>>").header("key","value"));
}

}

就您而言:

   @Autowired
private MockMvc mockMvc;

@Test
public void test() throws Exception {

String jsonString="{\"country\": \"India\", \"currency\": \"INR\", \"president\": \"Ram Nath Kovind\" } ";
mockMvc.perform(MockMvcRequestBuilders.post("/test").content(jsonString).header("code","12400f74dc4d8d69b713b1fe53f371c25a28a8c5fac2a91eea1f742ab4567c9c"));
}

输出:

JSON STRING {"country": "India", "currency": "INR", "president": "Ram Nath Kovind" }  header value 12400f74dc4d8d69b713b1fe53f371c25a28a8c5fac2a91eea1f742ab4567c9c

关于spring - spring mvc测试中访问请求体和请求头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46138006/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com