所以,我在我的项目中使用spring session。 如何使用它在项目中编写集成测试?我应该为春季会议内部模拟一些东西吗?或者使用嵌入式redis的任何合理方式?
我看到过去有一些@EnableEmbeddedRedis注释,但似乎已删除:https://github.com/spring-projects/spring-session/issues/248
//修改
我试图将MockHttpSession传递给
mockMvc.perform(post("/register").session(mockHttpSession)
但春天尝试并且无论如何都无法连接到redis。
答案 0 :(得分:8)
您可以创建自己的connectionfactory和redisserializer。然后spring boot将不会创建默认bean。
示例:
@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;
}
}
}
答案 1 :(得分:1)
好的,我只是通过在集成测试中使用配置文件来禁用redis
@ActiveProfiles("integrationtests")
class RegisterControllerTest extends Specification {...
并将@EnableRedisHttpSession解压缩到它自己的类:
@Configuration
@EnableRedisHttpSession
@Profile("!integrationtests")
public class RedisConfig {
}
它更像解决方案而不是解决方案,但我不需要在会话中测试任何内容。
答案 2 :(得分:0)
这项工作:
在您的HttpSessionConfig中定义配置处于活动状态的配置文件:
@EnableRedisHttpSession
@Profile("prod")
class HttpSessionConfig {
}
在application-prod.properties中添加:
#REDIS SERVER
spring.redis.host=xxxxxxxx
然后在你的application.properties of test add:
#REDIS SERVER
spring.data.redis.repositories.enabled=false
spring.session.store-type=none
答案 3 :(得分:0)
我不建议使用mockHttpSession,因为它会在测试中绕过与spring-session库的集成。我会
@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
public class ExampleControllerV2SpringSessionTest {
@Autowired
private WebApplicationContext wac;
@Autowired
private SessionRepository sessionRepository;
@Autowired
private SessionRepositoryFilter sessionRepositoryFilter;
//this is needed to test spring-session specific features
private MockMvc mockMvcWithSpringSession;
@Before
public void setup() throws URISyntaxException {
this.mockMvcWithSpringSession = MockMvcBuilders
.webAppContextSetup(wac)
.addFilter(sessionRepositoryFilter)
.build();
}
}
我知道在测试过程中总是准备好redis实例,我建议你使用这个属性spring.session.store-type=hash_map
来测试你的测试用例。