【问题标题】:Body is empty when using MockMvc使用 MockMvc 时正文为空
【发布时间】:2018-07-10 19:17:27
【问题描述】:
<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

【问题讨论】:

    标签: java spring-boot testing mockmvc


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-21
      • 2021-04-01
      • 1970-01-01
      • 2019-12-25
      • 1970-01-01
      • 2017-08-05
      • 1970-01-01
      相关资源
      最近更新 更多