如果控制器在方法中注入了 HttpServletRequest,如何使用 Mockito.when 测试 Spring Rest Controller

2023-12-23

我的控制器看起来像这样

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

测试看起来像这样

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

问题是我收到错误

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

如果我从控制器方法和测试中删除 HttpServletRequest ,这将起作用。


MockMvcRequestBuilders有两种方法

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

   public static MockHttpServletRequestBuilder get(URI uri) {

您可以根据您的要求使用第一个,如下所示

@Mock
HttpServletRequest req;


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

当然有几件事需要考虑

  1. 如果您使用的是,则需要初始化模拟@Mock (MockitoAnnotations.initMocks(this))
  2. 您需要模拟拨打的电话HttpServletRequest
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如果控制器在方法中注入了 HttpServletRequest,如何使用 Mockito.when 测试 Spring Rest Controller 的相关文章

随机推荐