5
<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>

It always gives empty body:

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

It is working fine when I use TestRestTemplate. But, when I use MockMvc and @MockBean, it always gives empty output. I have also used com.gargoylesoftware.htmlunit.WebClient. But, that also gives empty body. I don't know what is happening. Please help. Is it a version issue or I am doing something wrong? Spring boot version: 1.5.10

Ashish Sharma
  • 617
  • 6
  • 15

1 Answers1

-1

Your controller excute method of customerService. Right? Then you have to stub that method.

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

    this.mockMvc.perform(get("/url"))
        .andExpect(someThing);
}
Min Hyoung Hong
  • 1,102
  • 9
  • 13