簡體   English   中英

MockMVC和Mockito返回狀態預期<200>但<415>

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

我正在測試一個api端點,它可以從一個http海報(即PAW)中運行,但是我無法通過代碼進行測試。

我是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只包含一個屬性,一個布爾“成功”。

它正在測試的方法如下:

@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)

HTTP錯誤415不支持的媒體類型 - 表示您發送服務不支持的數據。 在這種情況下,這意味着您不在請求中設置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

您可能還缺少控制器類上的一些注釋。 確保使用@EnableWebMvc和@Controller

有關詳細信息,請查看此答案

您也可以添加接受

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM