如果控制器在方法中注入了HttpServletRequest,如何使用Mockito.Spring测试Spring Rest Controller [英] How to test Spring Rest Controller with Mockito.when if controller has HttpServletRequest injected in method

查看:132
本文介绍了如果控制器在方法中注入了HttpServletRequest,如何使用Mockito.Spring测试Spring Rest Controller的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控制器看起来像这样

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

测试看起来像这样

@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并进行测试,这将起作用.

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

推荐答案

MockMvcRequestBuilders有两种方法

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

当然要考虑的几件事

  1. 如果使用@Mock (MockitoAnnotations.initMocks(this))
  2. ,则需要初始化模拟
  3. 您需要模拟在HttpServletRequest
  4. 上进行的调用
  1. You need to initialize mocks if you are using @Mock (MockitoAnnotations.initMocks(this))
  2. You need to mock the calls made on HttpServletRequest

这篇关于如果控制器在方法中注入了HttpServletRequest,如何使用Mockito.Spring测试Spring Rest Controller的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆