How to test Spring Rest Controller with Mockito.when if controller has HttpServletRequest injected in method

女生的网名这么多〃 提交于 2019-12-24 07:08:03

问题


My Controller looks like this

@GetMapping("/networks/{networkId}")
public Resource<Network> getNetwork(
  @PathVariable("networkId") UUID id,
  HttpServletRequest request) {

    Resource<Network> network = networkClient.getNetwork(id);

    network.removeLinks();
    network.add(LinkHelper.getNetworkObjectLinkArray(request, id));

    return network;
}

And test looks like so

@Test
public void getNetwork() throws Exception {
    Resource<Network> networkResource = createSampleNetwork(organizationId, "Test Network 01");

    MockHttpServletRequest mockedRequest = new  MockHttpServletRequest(context.getServletContext()); 
    UUID networkId = HalParser.parseUUIDFromLink(networkResource.getId());
    when(networkRestController.getNetwork(networkId, mockedRequest))
        .thenReturn(networkResource);

    mockMvc.perform(get("/networks/" + HalParser.parseUUIDFromLink(networkResource.getId()))
        .accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())
        .andDo(print())
        .andDo(document.document(
                  responseFields(
                      fieldWithPath("name").description("The network's name"),
                      fieldWithPath("caName").description("The network's ca name"),
                      fieldWithPath("productFamily").description("The network's product family"),
                      fieldWithPath("productVersion").description("The version of the network core software"),
                      fieldWithPath("status").description("Provisioning status of the network"),
                      fieldWithPath("createdAt").description("Record creation time"),
                      fieldWithPath("updatedAt").description("Record last modification time"),
                      fieldWithPath("_links").description("<<resources-index-links,Links>> to other resources")
                  )
          ));
}

The issue is I am getting the error

"Method threw 'org.mockito.exceptions.misusing.UnfinishedStubbingException' exception. Cannot evaluate MyRestController$$EnhancerByMockitoWithCGLIB$$6fa8dd17.toString()"

This works if I remove the HttpServletRequest from the controller method and test.


回答1:


MockMvcRequestBuilders has two methods

   public static MockHttpServletRequestBuilder get(String urlTemplate, Object... uriVars) 

   public static MockHttpServletRequestBuilder get(URI uri) {

You can use the first one for your requirement, like this

@Mock
HttpServletRequest req;


 mockMvc.perform(get("/networks/" + HalParser.parseUUIDFromLink(networkResource.getId()), req)
        .accept(MediaType.APPLICATION_JSON))
        .......

of course couple of things to consider

  1. You need to initialize mocks if you are using @Mock (MockitoAnnotations.initMocks(this))
  2. You need to mock the calls made on HttpServletRequest


来源:https://stackoverflow.com/questions/48156808/how-to-test-spring-rest-controller-with-mockito-when-if-controller-has-httpservl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!