内容简介:在我们进行开发过程中,单元测试是保证代码质量的最有利工具,我们每个方法都要有对应的测试,在目前开发规范中,主要把测试分为单元测试和集成测试,我们的公用方法都要写自己的单元测试,而web api的每个接口都要写集成测试。分布式环境下,单机的session是不能满足我们需求的,所以session存储的中间件就出现了,比较常用的有数据库和redis两种,在springboot框架里,也集成了redis session的实现。在测试环境里,我们可以使用mockSession来实现对session的模拟,在进行mvc
简单谈谈
在我们进行开发过程中,单元测试是保证代码质量的最有利工具,我们每个方法都要有对应的测试,在目前开发规范中,主要把测试分为单元测试和集成测试,我们的公用方法都要写自己的单元测试,而web api的每个接口都要写集成测试。
redis session
分布式环境下,单机的session是不能满足我们需求的,所以session存储的中间件就出现了,比较常用的有数据库和 redis 两种,在springboot框架里,也集成了redis session的实现。
安装依赖包
'org.springframework.session:spring-session-data-redis',
配置注入
/** * Spring Session,代替了传统的session. */ @Configuration @EnableRedisHttpSession public class HttpSessionConfig { @Autowired private RedisConnectionFactory redisConnectionFactory; /** * redis 配置. */ @Bean public RedisTemplate redisTemplate() { RedisTemplate redisTemplate = new RedisTemplate(); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new StringRedisSerializer()); redisTemplate.setConnectionFactory(redisConnectionFactory); return redisTemplate; } }
使用session
@Autowired HttpSession httpSession;
mockSession
在测试环境里,我们可以使用mockSession来实现对session的模拟,在进行mvc请求时,把session带在请求头上就可以了。
MockHttpSession session; @Autowired private WebApplicationContext webApplicationContext; private MockMvc mockMvc; * 初始化. */ @Before public void init() { this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); session = new MockHttpSession(); session.setAttribute("distributor", DistributorBaseInfo.builder().id(1L).build()); } @Test public void testSession() throws Exception { mockMvc .perform( get("/v1/api/user") .accept(MediaType.APPLICATION_JSON_UTF8) .session(session) .param("pageCurrent", "1") .param("pageSize", "1")) .andExpect(status().isOk()) .andExpect(jsonPath("$.records.length()").value(1)); }
上面代码中展示了,如何在单元测试中模拟session,事实上,我们http请求里的session已经被mockSession覆盖了,我们在对应的接口上打断点可以看到,session使用的是mock出来的。
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Implementing Responsive Design
Tim Kadlec / New Riders / 2012-7-31 / GBP 27.99
New devices and platforms emerge daily. Browsers iterate at a remarkable pace. Faced with this volatile landscape we can either struggle for control or we can embrace the inherent flexibility of the w......一起来看看 《Implementing Responsive Design》 这本书的介绍吧!