【问题标题】:How to make a POST test request in REST MVC Spring test如何在 REST MVC Spring 测试中发出 POST 测试请求
【发布时间】:2017-05-22 09:29:09
【问题描述】:

我正在使用: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)

【问题讨论】:

  • 你能在你的日志文件中包含任何输出吗?
  • @emeraldjava 我已经包含了它

标签: java spring rest spring-mvc mockito


【解决方案1】:

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

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

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

【讨论】:

  • 你说的我都试过了。但是我收到了相同的错误消息“400”,没有任何变化。 mockMvc.perform(post("/users").contentType(MediaType.APPLICATION_JSON).content(user1.toString()))
  • 好的。最后我明白了你所说的,我成功地将我的用户作为字符串传递。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-08
  • 1970-01-01
  • 2018-06-10
  • 1970-01-01
  • 2020-03-26
  • 2017-10-28
相关资源
最近更新 更多