首页 > 解决方案 > 如何在 HttpServletRequest 中设置标头

问题描述

我正在为我的一个班级编写 Junit Test 班级,班级有 POST 休息方法。我需要将一些标头发送到 POST 方法。我正在使用 HttpServletRequest 发送请求。下面是我的测试类方法:

void setup () throws Exception {
    LOGGER.info(" Setting up the test data....");
    System.out.println(" Method setup : Start");
    Map<String, String> headers = new HashMap<>();
    headers.put("content-type", "application/json");
    headers.put("cnt", "leader");
    Enumeration<String> headerNames = Collections.enumeration(headers.keySet());
    
    mockRequest = mock( HttpServletRequest.class );
    
    when(mockRequest.getHeaderNames()).thenReturn(headerNames);
    when(mockRequest.getHeaders("content-type")).thenReturn("application/json");
    mockResponse = mock(HttpServletResponse.class);
    mockResponse.setContentType("application/json");
    try {           
        JsonReader jsonReader = Json.createReader(new StringReader(strContent));
        jsonRequestObject = jsonReader.readObject();
        jsonReader.close();         
        System.out.println(" jsonRequestObject : {} "+ jsonRequestObject);
        myService.callMyService(mockRequest, jsonRequestObject);
    } catch (Exception e) {
        throw e;
    }
}

标签: javajunitmockito

解决方案


推荐阅读