Java MockMVC 和 Mockito 返回 Status 预期为 <200> 但为 <415>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23569213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 00:02:17  来源:igfitidea点击:

MockMVC and Mockito returns Status expected <200> but was <415>

javaspringspring-mvcmockito

提问by Ben Taliadoros

I'm testing an api endpoint which works from a http poster (namely PAW) but I cant get a test in the code to pass.

我正在测试一个从 http 海报(即 PAW)工作的 api 端点,但我无法在代码中进行测试以通过。

I'm new to both Mockito and MockMVC so any help would be appreciated.

我是 Mockito 和 MockMVC 的新手,所以任何帮助将不胜感激。

Test below:

测试如下:

 @Test
 public void createPaymentTest() throws Exception {
    User user = new User("ben", "password", "[email protected]");

    SuccessResponseDTO successDTO = new SuccessResponseDTO();
    successDTO.setSuccess(true);

    when(userService.getLoggedInUser()).thenReturn(user);
    when(paymentService.makePayment(Mockito.any(PaymentRequestDTO.class), Mockito.any(User.class))).thenReturn(successDTO.getSuccess());

    this.mockMvc.perform(post("/payment")).andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultHandlers.print())
            .andExpect(jsonPath("$.success").value(successDTO.getSuccess()));

}

SuccessResponseDTO just contains one attribute, a boolean 'success'.

SuccessResponseDTO 只包含一个属性,一个布尔值“成功”。

The method it's testing is below:

它的测试方法如下:

@RequestMapping(value = "/payment", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public SuccessResponseDTO createPayment(@RequestBody PaymentRequestDTO payment) {
    User loggedInUser = userService.getLoggedInUser();
    LOGGER.info("Logged in user found...creating payment...");

    Assert.notNull(payment.getAccountId(), "Missing user account id");
    Assert.notNull(payment.getPayeeAccountNumber(), "Missing payee acount number");
    Assert.notNull(payment.getPayeeName(), "Missing payee name");
    Assert.notNull(payment.getPayeeSortCode(), "Missing payee sort code");
    Assert.notNull(payment.getPaymentAmount(), "Missing payee amount");
    Assert.notNull(payment.getPaymentDescription(), "Missing payment description");

    Boolean paymentResult = paymentService.makePayment(payment, loggedInUser);

    SuccessResponseDTO successResponse = new SuccessResponseDTO();

    successResponse.setSuccess(paymentResult);

    return successResponse;
}

Can anyone shed light on the stack trace:

任何人都可以阐明堆栈跟踪:

java.lang.AssertionError: Status expected:<200> but was:<415>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:60)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:89)
at org.springframework.test.web.servlet.result.StatusResultMatchers.match(StatusResultMatchers.java:546)
at org.springframework.test.web.servlet.MockMvc.andExpect(MockMvc.java:141)
at com.capco.living.controller.PaymentControllerTest.createPaymentTest(PaymentControllerTest.java:69)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access
this.mockMvc.perform(post("/payment").contentType(MediaType.APPLICATION_JSON)
    .content("{\"json\":\"request to be send\"}"))
    .andExpect(status().isOk())
    .and_the_rest_of_validation_part
0(ParentRunner.java:53) at org.junit.runners.ParentRunner.evaluate(ParentRunner.java:229) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

采纳答案by swist

HTTP Error 415 Unsupported media type- means that you send the data which is not supported by the service. In this case it means that you don't set the Content-Type header and actual content in the request. I suppose the JSON is expected content, so your call should look like this:

HTTP 错误 415 不支持的媒体类型- 意味着您发送的数据不受服务支持。在这种情况下,这意味着您没有在请求中设置 Content-Type 标头和实际内容。我想 JSON 是预期的内容,所以你的调用应该是这样的:

 mockMvc.perform(post("/api/sender/sms/")
            .accept(MediaType.APPLICATION_JSON_UTF8)
            .contentType(MediaType.APPLICATION_JSON_UTF8)
            .content("{ \"serviceName\":\"serviceName\",  \"apiId\":\"apiId\",  \"to\":\"to\",  \"msg\":\"msg\" }")
    )
        .andExpect(MockMvcResultMatchers.status().isOk())
        .andReturn();

回答by Ann Kilzer

You might also be missing some annotations on your controller class. Make sure you use @EnableWebMvc and @Controller

您可能还缺少控制器类上的一些注释。确保使用 @EnableWebMvc 和 @Controller

Check out this answer for details

查看此答案以了解详细信息

回答by Sergey Yurov

Also you might add accept

你也可以添加接受

##代码##