当前位置: 首页 > news >正文

SpringBoot:使用spring-boot-test对web应用做单元测试时如何测试Filter?

对SpringBoot的Web应用做单元测试时,一般会使用spring-boot-test,pom.xml中会添加如下内容:

		<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>

代码举例如下:

import static org.junit.jupiter.api.Assertions.assertEquals;import javax.annotation.Resource;import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;import com.test.protobuf.App;@RunWith(SpringRunner.class)
@SpringBootTest(classes = App.class)
public class WebAppTester {@Resourceprivate WebApplicationContext ctx = null;private MockMvc mockMvc = null;@Beforepublic void setupMockMvc() throws Exception {DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(ctx);this.mockMvc = builder.build();}@Testpublic void test01() throws Exception {String result = doHttpAsyncTest(mockMvc, "/admin/health", "", null);assertEquals("ok", result);}public String doHttpAsyncTest(MockMvc mockMvc, String uri, String httpBody, HttpHeaders httpHeaders)throws Exception {MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post(uri).contentType(MediaType.APPLICATION_JSON);if (httpHeaders != null) {builder.headers(httpHeaders);}MvcResult result = mockMvc.perform(builder.content(httpBody)).andReturn();String httpRespBody = mockMvc.perform(MockMvcRequestBuilders.asyncDispatch(result)).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)).andReturn().getResponse().getContentAsString();return httpRespBody;}}

如果应用中以如下方式添加了Filter的话,使用以上代码无法测试这些Filter:

import java.io.IOException;import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;public class TestFilter implements Filter {private String checkUrl = "/";@Overridepublic void init(FilterConfig config) throws ServletException {String checkUrl = config.getInitParameter("checkUrl");if (checkUrl != null) {this.checkUrl = checkUrl;}}@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException {HttpServletRequest httpReqt = (HttpServletRequest) request;String reqtUrl = httpReqt.getRequestURI();if (!reqtUrl.startsWith(checkUrl)) {chain.doFilter(request, response);return;}HttpServletResponse httpResp = (HttpServletResponse) response;httpResp.setStatus(200);httpResp.setContentType("text/plain");httpResp.getWriter().write("ok");return;}}
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Configuration;@Configuration
public class FilterRegistrationConfig {public FilterRegistrationBean<TestFilter> testFilter() {FilterRegistrationBean<TestFilter> reg = new FilterRegistrationBean<TestFilter>();reg.setFilter(new TestFilter());reg.addInitParameter("checkUrl", "/admin/");reg.setName("TestFilter");return reg;}
}

如果想把这些Filter也测试到,需要在setupMockMvc方法中将Filter注册并初始化一下,代码如下:

import com.test.protobuf.App;@RunWith(SpringRunner.class)
@SpringBootTest(classes = App.class)
public class WebAppTester {@Resourceprivate WebApplicationContext ctx = null;private MockMvc mockMvc = null;@Resourceprivate FilterRegistrationBean<?>[] filterRegistrationBean = null;@Beforepublic void setupMockMvc() throws Exception {DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(ctx);for (FilterRegistrationBean<?> bean : filterRegistrationBean) {MockFilterConfig filterConfig = new MockFilterConfig();for (Entry<String, String> params : bean.getInitParameters().entrySet()) {filterConfig.addInitParameter(params.getKey(), params.getValue());}Filter filter = bean.getFilter();filter.init(filterConfig);builder.addFilter(filter, bean.getUrlPatterns().toArray(new String[0]));}this.mockMvc = builder.build();}
......
}

http://www.lryc.cn/news/538177.html

相关文章:

  • 解锁 Java 回调函数:异步编程与事件处理的利器
  • 记PasteSpider部署工具的Windows.IIS版本开发过程之草稿-Web.IIS.Administration解读(5)
  • MySQL Workbench安装教程以及菜单汉化
  • 【ISO 14229-1:2023 UDS诊断全量测试用例清单系列:第十节】
  • Python的imutils库详细介绍
  • 常用查找算法整理(顺序查找、二分查找、插值查找、斐波那契查找、哈希查找、二叉排序树查找、平衡二叉树查找、红黑树查找、B树和B+树查找、分块查找)
  • 2526考研资料分享 百度网盘
  • 网络编程(24)——实现带参数的http-get请求
  • 东方财富股吧发帖与评论爬虫
  • 【Elasticsearch】match_bool_prefix查询
  • 微信小程序image组件mode属性详解
  • 数据结构:最小生成树
  • C语言-章节 4:函数的定义与声明 ——「神秘法术的卷轴」
  • 《云原生安全攻防》-- K8s镜像安全:镜像全生命周期安全管理
  • uniapp商城之首页模块
  • 【Javascript Day13、14、15、16】
  • linux 板子的wifi模块连上路由器后,用udhcpc给板子wifi分配ip,udhcpc获取到ip,但没有写入wlan0网卡上
  • openGauss 3.0 数据库在线实训课程13: 学习逻辑结构:表管理1
  • 网络编程-
  • 基于单片机的常规肺活量SVC简单计算
  • 【PostgreSQL】PG在windows下的安装
  • 电动汽车电池监测平台系统设计(论文+源码+图纸)
  • 基于和声搜索(Harmony Search, HS)的多中心点选址优化算法matlab仿真
  • 单链表的概念,结构和优缺点
  • SpringBoot+数据可视化的奶茶点单购物平台(程序+论文+讲解+安装+调试+售后)
  • 深入理解 Vue3 中 ref 与 reactive 的区别及应用
  • TDengine 客户端连接工具 taos-Cli
  • Linux(ubuntu)下载ollama速度慢解决办法
  • Mac安装JD-GUI
  • Jenkins 配置 Git Parameter 四