簡體   English   中英

使用MockMvc時,正文為空

[英]Body is empty when using MockMvc

<pre><code>

@RunWith(SpringRunner.class) 
@WebMvcTest(CustomerController.class) 
public class CustomerControllerMvcTest {

    @Autowired  
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @MockBean   
    private ICustomerService customerService;

    @Before     
    public void before() {
    MockitoAnnotations.initMocks(this);
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
                       .dispatchOptions(true).build();  
    }

    @Test   
    public void getTaskByUserdId1() throws Exception {      
       String expectedOutput = "{\"id\":3,\"name\":\"vikas\"}";
       this.mockMvc.perform(MockMvcRequestBuilders.get("/customer/get/vikas")
       .accept(MediaType.APPLICATION_JSON_UTF8_VALUE))
       .andExpect(status().isOk())
       .andExpect(content().string(expectedOutput));
    }

    @Test   
    public void getTaskByUserdId2() throws Exception {      
        String expectedOutput = "{\"id\":3,\"name\":\"vikas\"}";
        this.mockMvc.perform(get("/customer/get/vikas"))
        .andDo(print())
        .andExpect(status().isOk())
        .andExpect(content().string(containsString(expectedOutput)));
    }
}

</code> </pre>

它總是給空身:

<pre>
<code>

MockHttpServletRequest:

      HTTP Method = GET
      Request URI = /customer/get/vikas
       Parameters = {}
          Headers = {}

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {}
     Content type = null
             Body = 
    Forwarded URL = null    Redirected URL = null
          Cookies = []

</code>
</pre>

我使用TestRestTemplate時工作正常。 但是,當我使用MockMvc@MockBean時 ,它總是提供空輸出。 我也使用過com.gargoylesoftware.htmlunit.WebClient 但是,這也給空體。 我不知道發生了什么。 請幫忙。 這是一個版本問題還是我做錯了什么? Spring boot版本:1.5.10

您的控制器執行customerService的方法。 對? 然后你必須存根該方法。

@Test
public void testMethod() throws Exception {
    when(customerService.doSomething())      
        .thenReturn(mockResult);              // you need to make this code

    this.mockMvc.perform(get("/url"))
        .andExpect(someThing);
}

暫無
暫無

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

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