redisSession和mockSession

简单谈谈

在我们进行开发过程中,单元测试是保证代码质量的最有利工具,我们每个方法都要有对应的测试,在目前开发规范中,主要把测试分为单元测试和集成测试,我们的公用方法都要写自己的单元测试,而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出来的。

愿与诸君共进步,大量的面试题及答案还有资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化、分布式架构等这些成为架构师必备的知识体系,可以微信搜索539413949获取,最后祝大家都能拿到自己心仪的offer

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容