java mock http_Java MockHttpServletRequest.setParameters方法代码示例

在单元测试中,使用MockHttpServletRequest模拟HTTP请求。通过设置方法、路径、参数、内容类型等,创建一个完整的请求对象。然后,通过MockHttpServletResponse获取响应内容并进行断言验证。
摘要由CSDN通过智能技术生成

import org.springframework.mock.web.MockHttpServletRequest; //导入方法依赖的package包/类

@Test

public void testIncludeNestedWithDefault() throws Exception {

Node root = new Node(1L, null, null);

Locale engLocale = new Locale(1L, java.util.Locale.ENGLISH);

Node child1 = new Node(2L, root, Collections.emptySet());

NodeComment child1Comment = new NodeComment(1L, "Child 1", child1, engLocale);

child1.setNodeComments(new LinkedHashSet<>(Collections.singleton(child1Comment)));

Node child2 = new Node(3L, root, Collections.emptySet(), Collections.emptySet());

root.setChildren(new LinkedHashSet<>(Arrays.asList(child1, child2)));

nodeRepository.save(root);

nodeRepository.save(child1);

nodeRepository.save(child2);

MockHttpServletRequest request = new MockHttpServletRequest(servletContext);

request.setMethod("GET");

request.setServletPath("/api");

request.setPathInfo("/nodes/1");

request.setRequestURI("/api/nodes/1");

request.setQueryString("include[nodes]=children.nodeComments");

request.setContentType(HttpHeaders.JSONAPI_CONTENT_TYPE);

Map params = new HashMap<>();

params.put("include[nodes]", "children.nodeComments.langLocale");

request.setParameters(params);

request.addHeader("Accept", "*/*");

MockHttpServletResponse response = new MockHttpServletResponse();

servlet.service(request, response);

String responseContent = response.getContentAsString();

assertTopLevelNodesCorrectWithChildren(responseContent);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值