在spring mvc test中访问请求体和请求头

时间:2017-09-10 06:45:28

标签: spring spring-boot model-view-controller junit mockmvc

我创建了一个spring boot应用程序,这就是我的控制器的样子。我使用postman在请求体中发送json,在请求头中发送一个字符串,然后进一步散列json并将其与请求头获取的字符串进行比较。问题是我不知道获取请求体和请求头以便使用MockMvc测试相应的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();
    }
}

请帮助我在上面的代码中从请求中检索正文和标题值并将散列(正文)与标题值等同

1 个答案:

答案 0 :(得分:5)

@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