如何在REST MVC Spring测试中发出POST测试请求

时间:2017-05-22 09:29:10

标签: java spring rest spring-mvc mockito

我正在使用:Mockito,Spring test和Hamcrest。

我有一个像这样的用户控制器类:

@RestController 
public class UserController {

private UserResource userResource;

@RequestMapping(value = "/users", method = RequestMethod.POST)
public Response create(@Valid @RequestParam String json) throws ResourceException {
    System.out.println(json);
    Response response = userResource.insert(json);
    return response;
}

}

这是我的考验。我的方法userResource.insert使用户json重新创建用户的实例并保留它:

@Test
public void testPost() throws Exception{
    JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder();
    JsonObject user1 = jsonObjectBuilder.add("pseudo", "pseudo1").add("accessToken","accesstoken").add("picture","picture").build();
    System.out.println(user1.toString());
    User user =  new User();
    user.setId(1);
    user.setPseudo("pseudo1");
    user.setAccessToken("accesstoken");
    user.setPicture("picture");
    RestResponse<User> restResponse = new RestResponse<User>();
    restResponse.setData(user);
    Response response = restResponse.throw200Ok();

    when(userResource.insert(user1.toString())).thenReturn(response);
    mockMvc.perform(post("/users").accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(content().contentType("application/json;charset=UTF-8"))
            .andExpect(jsonPath("$..id").value(1))
            .andExpect(jsonPath("$..pseudo").value("pseudo"))
            .andExpect(jsonPath("$..password").value("password"))
            .andExpect(jsonPath("$..picture").value("picture"));


    verify(userResource, times(1)).insert(user1.toString());
}

但是,我的测试失败了,当我运行它时出现此消息错误:

java.lang.AssertionError: Status 
Expected :200
Actual   :400

这意味着我正在尝试一个糟糕的请求,但我已经使用我的REST服务器测试它并且它是成功的 我不明白我的错误在哪里。我之前做过GET和DELETE测试没有错误。

日志输出:

mai 22, 2017 11:19:33 AM  org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping register
INFOS: Mapped "{[/users/{id}],methods=[GET]}" onto public 
...
INFOS: Looking for @ControllerAdvice:   org.springframework.test.web.servlet.setup.StubWebApplicationContext@5f2f57 7
mai 22, 2017 11:19:33 AM   org.springframework.mock.web.MockServletContext log
INFOS: Initializing Spring FrameworkServlet ''
mai 22, 2017 11:19:33 AM   org.springframework.test.web.servlet.TestDispatcherServlet initServletBean
INFOS: FrameworkServlet '': initialization started
mai 22, 2017 11:19:33 AM   org.springframework.test.web.servlet.TestDispatcherServlet initServletBean
INFOS: FrameworkServlet '': initialization completed in 1 ms
{"pseudo":"pseudo1","accessToken":"accesstoken","picture":"picture"}

java.lang.AssertionError: Status 
Expected :200
Actual   :400
<Click to see difference>


at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:54)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:81)
...
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
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 com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

1 个答案:

答案 0 :(得分:2)

我认为错误在“接受”部分,应该有“contentType”:

mockMvc.perform(post("/users").contentType(MediaType.APPLICATION_JSON)).content(some_json_data)...

另据我所知,您不会将任何数据发布到“/ users”端点。