redisSession和mockSession

簡單談談

在咱們進行開發過程當中,單元測試是保證代碼質量的最有利工具,咱們每一個方法都要有對應的測試,在目前開發規範中,主要把測試分爲單元測試和集成測試,咱們的公用方法都要寫本身的單元測試,而web api的每一個接口都要寫集成測試。web

redis session

分佈式環境下,單機的session是不能知足咱們需求的,因此session存儲的中間件就出現了,比較經常使用的有數據庫和redis兩種,在springboot框架裏,也集成了redis session的實現。redis

安裝依賴包

'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帶在請求頭上就能夠了。spring

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出來的。數據庫

相關文章
相關標籤/搜索