简体   繁体   中英

Testing POST request controller with mockito

I am trying to test whether the Object that a client sends to the server really gets added to the db by the controller with mockito. So I want to test the response of the server and whether the object that got sent really gets saved in db. Here is what I have in terms of code=

My Test:

@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
public class UserControllerTest
{
@Autowired
private MockMvc mockMvc;

@MockBean
private UserRepository userRepository;

@Test
public void testAddUserToDb() throws Exception
{
    User objToAdd = new User();
    objToAdd.setId(1);
    objToAdd.setUserID(3);
    objToAdd.setScore(55);
    objToAdd.setName("Tom");

    Gson gson = new Gson();
    String jsonString = gson.toJson(objToAdd);

    when(userRepository.save(any(User.class))).thenReturn(objToAdd);

    mockMvc.perform(post("/user/add").contentType(MediaType.APPLICATION_JSON_UTF8).content(jsonString))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(jsonPath("$.id").value(1))
            .andExpect(jsonPath("$.userID").value(3))
            .andExpect(jsonPath("$.score").value(55))
            .andExpect(jsonPath("$.name").value("Tim"));

    ArgumentCaptor<User> userArgumentCaptor = ArgumentCaptor.forClass(User.class);
    verify(userRepository, times(1)).save(userArgumentCaptor.capture());
    verifyNoMoreInteractions(userRepository);

    User userArgument = userArgumentCaptor.getValue();
    assertEquals(is(1), userArgument .getId());
    assertEquals(is("Tom"), userArgument .getName());
    assertEquals(is(3), userArgument .getUserID());
    assertEquals(is(55), userArgument .getScore());
}
}

My Controller method:

@RestController
@RequestMapping("/user")
public class UserController
{
@Autowired
private UserRepository userRepository;

@PostMapping("/add")
public ResponseEntity AddUser(@RequestBody User user) throws Exception
{
    userRepository.save(user);
    return ResponseEntity.ok(HttpStatus.OK);
}
}

Error log:

MockHttpServletRequest:
  HTTP Method = POST
  Request URI = /user/add
   Parameters = {}
      Headers = [Content-Type:"application/json;charset=UTF-8"]
         Body = {"id":1,"userID":3,"name":"veg","score":55}
Session Attrs = {}

... not so important code later ...

MockHttpServletResponse:
       Status = 200
Error message = null
      Headers = [Content-Type:"application/json;charset=UTF-8"]
 Content type = application/json;charset=UTF-8
         Body = "OK"
Forwarded URL = null
   Redirected URL = null
          Cookies = []

java.lang.AssertionError: No value at JSON path "$.id"

at org.springframework.test.util.JsonPathExpectationsHelper.evaluateJsonPath(JsonPathExpectationsHelper.java:295)
at org.springframework.test.util.JsonPathExpectationsHelper.assertValue(JsonPathExpectationsHelper.java:98)
at org.springframework.test.web.servlet.result.JsonPathResultMatchers.lambda$value$2(JsonPathResultMatchers.java:111)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:195)
at spring.controller.UserControllerTest.AddUser(UserControllerTest.java:59)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)

Expectations (string like .andExpect(jsonPath("$.id").value(1)) ) are used to check response, not a request. Your response is just 200 OK without response body (according to your controller).

The following should work correctly:

mockMvc.perform(post("/user/add")
    .contentType(MediaType.APPLICATION_JSON_UTF8)
    .content(jsonString))
    .andExpect(status().isOk());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM