3

redisSession和mockSession

 5 years ago
source link: http://www.cnblogs.com/lori/p/10288694.html?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

简单谈谈

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK