0

Can anyone asssist how to write mockMVC for the controller? I have come up with mockMVC however i am stuck and not sure how to test further

From UI

  1. User selectes from the drop down and does the form submit with select ID as name (which is @RequestBody String name in the controller)

My Controller

 @PostMapping("/api/user")
public User getSearch(@RequestBody String name) {
    User user=new User();   
    String result=userService.findByUser(name);
    user.setUsername(result);
    return user;

}

My Mock MVC Class

@Autowired
private WebApplicationContext webApplicationContext;

private MockMvc mockMvc;

@Test
public void testUser() throws Exception {
    mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    mockMvc.perform(post("/api/user")
    .accept(MediaType.APPLICATION_JSON))
    .andExpect(status().isOk());
}

Any help will be great

kulu makani
  • 1
  • 1
  • 2

1 Answers1

0

You were close. You don't need however APPLICATION_JSON as you are only passing a string.

@Autowired
private YourController yourController;

@Before
public void setup() {
    this.mockMvc = MockMvcBuilders.standaloneSetup(yourController)
            .build();
}

@Test
public void requestBody() throws Exception {
    this.mockMvc.perform(
            post("/api/user")
                .contentType(MediaType.TEXT_PLAIN)
                .content("foobar")
            .andExpect(status().isOk());

Also, add @ResponseBody to your method inside the controller.

@Test
public void requestBody() throws Exception {
  this.mockMvc.perform(
    post("/api/user")
    .contentType(MediaType.TEXT_PLAIN)
    .content("foobar")
    .andExpect(status().isOk()).andExpect(content().contentTypeCompatibleWith("application/json"))
    .andExpect(jsonPath("$name", is("foobar")));
ISlimani
  • 1,643
  • 14
  • 16