Access request body and request header in spring mvc test

24.6k views Asked by At

I have created a spring boot application and this is how my controller looks like. I am using postman to send json in request body and a string in request header, then further hashing the json and comparing it with the string got by request header. The problem is I am unaware of getting the request body and request header in order to test the respective Controller class using MockMvc.

Controller Logic

@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);
    }
}

Test Logic

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();
    }
}

Please help me out in the above code to retrieve the body and header value from request and equating the hash(body) with header value

1

There are 1 answers

7
Barath On BEST ANSWER
@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"));
    }

}

In your case:

   @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"));
}

output:

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