MockMVC和Mockito返回预期状态,< 200>但实际上< 415>

igsr9ssn  于 2023-01-30  发布在  其他
关注(0)|答案(3)|浏览(322)

我正在测试一个从http海报(即PAW)工作的api端点,但我不能让代码中的测试通过。
我是Mockito和MockMVC的新手,所以任何帮助都将不胜感激。
测试如下:

@Test
 public void createPaymentTest() throws Exception {
    User user = new User("ben", "password", "a@a.com");

    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只包含一个属性,即布尔值"success"。
其测试方法如下:

@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;
}

有人能解释一下堆栈跟踪吗:

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$5.match(StatusResultMatchers.java:546)
at org.springframework.test.web.servlet.MockMvc$1.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$1.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$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.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)
kmbjn2e3

kmbjn2e31#

HTTP Error 415 Unsupported media type-表示您发送了服务不支持的数据。在这种情况下,这意味着您没有设置请求中的Content-Type头和实际内容。我假设JSON是预期内容,因此您的调用应如下所示:

this.mockMvc.perform(post("/payment").contentType(MediaType.APPLICATION_JSON)
    .content("{\"json\":\"request to be send\"}"))
    .andExpect(status().isOk())
    .and_the_rest_of_validation_part
wlp8pajw

wlp8pajw2#

控制器类上可能还缺少一些注解。请确保使用@EnableWebMvc和@Controller
checkout this answer for details

ujv3wf0j

ujv3wf0j3#

您还可以添加accept

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();

相关问题