Spring session with redis - how to mock it in integration tests?

freakman picture freakman · Oct 8, 2015 · Viewed 9.3k times · Source

So, Im using spring session in my project. How to write integration tests in project using it? Should I mock something for spring session internals? Or any reasonable way to use embedded redis?

I saw there was some @EnableEmbeddedRedis annotation in past, but seems it was removed: https://github.com/spring-projects/spring-session/issues/248

//edit

Ive tried to pass MockHttpSession to

mockMvc.perform(post("/register").session(mockHttpSession)

but spring tries and fails to connect to redis anyway.

Answer

Dmitriy Kosolobov picture Dmitriy Kosolobov · Mar 24, 2016

You can create your own connectionfactory and the redisserializer. Then spring boot won't create their default beans.

Example:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
public class ApplicationTest
{

    @Test
    public void contextLoads()
    {
    }


    @EnableRedisHttpSession
    @Configuration
    static class Config
    {
        @Bean
        @SuppressWarnings("unchecked")
        public RedisSerializer<Object> defaultRedisSerializer()
        {
            return Mockito.mock(RedisSerializer.class);
        }


        @Bean
        public RedisConnectionFactory connectionFactory()
        {
            RedisConnectionFactory factory = Mockito.mock(RedisConnectionFactory.class);
            RedisConnection connection = Mockito.mock(RedisConnection.class);
            Mockito.when(factory.getConnection()).thenReturn(connection);

            return factory;
        }
    }
}