当前位置: 首页 > 知识库问答 >
问题:

在junit测试中禁用RedisHttpSessionConfiguration

刘运浩
2023-03-14

我正在使用spring-bootspring-session构建一个简单的rest API。生产应用程序应该使用redis-session实现,而测试应该使用默认的(非Redis)Spring-Session。

但是,当在项目中声明spring-boot-starter-redismaven依赖项时,spring-boot将自动创建org.springframework.session.data.redis.config.annotation.web.http.redisHttpSessionConfiguration,而在测试配置中没有@enableRedisHttpSession注释。

我的设置

申请代码:

// base session config for both prod/dev and test/ci
public class BaseSessionConfig {

  @Bean
  public HeaderHttpSessionStrategy sessionStrategy() {
    return new HeaderHttpSessionStrategy();
  }

}

// enable the redis session only in these profiles
@Configuration
@EnableRedisHttpSession
@Profile({"prod", "dev", "local", "vagrant"})
public class RedisSessionConfig extends BaseSessionConfig {


}

测试:

@WebIntegrationTest
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {MyApplication.class, MyTestApplicationConfig.class})
public class AuthenticationResourceTest {

  private RestTemplate restTemplate = new TestRestTemplate();

  @Test
  public void testUnauthenticated() {

    HttpHeaders headers = restTemplate.getForEntity("http://localhost:8080/api/session", String.class).getHeaders();

    // ...    
  }

}

// session configuration for the test environments
// no redis enabled    
@Configuration
@Profile({"ci", "test"})
public class MyTestApplicationConfig extends BaseSessionConfig {


}
java.lang.IllegalStateException: Failed to load ApplicationContext

    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:228)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:230)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:249)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:119)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'enableRedisKeyspaceNotificationsInitializer' defined in class path resource [org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfiguration.class]: Invocation of init method failed; nested exception is org.springframework.data.redis.RedisConnectionFailureException: Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:764)
    at org.springframework.boot.SpringApplication.doRun(SpringApplication.java:357)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:305)
    at org.springframework.boot.test.SpringApplicationContextLoader.loadContext(SpringApplicationContextLoader.java:98)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
    ... 24 more
Caused by: org.springframework.data.redis.RedisConnectionFailureException: Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
    at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.fetchJedisConnector(JedisConnectionFactory.java:162)
    at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.getConnection(JedisConnectionFactory.java:251)
    at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.getConnection(JedisConnectionFactory.java:58)
    at org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration$EnableRedisKeyspaceNotificationsInitializer.afterPropertiesSet(RedisHttpSessionConfiguration.java:166)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
    ... 40 more
Caused by: redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
    at redis.clients.util.Pool.getResource(Pool.java:50)
    at redis.clients.jedis.JedisPool.getResource(JedisPool.java:99)
    at redis.clients.jedis.JedisPool.getResource(JedisPool.java:12)
    at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.fetchJedisConnector(JedisConnectionFactory.java:155)
    ... 45 more
Caused by: redis.clients.jedis.exceptions.JedisConnectionException: java.net.ConnectException: Connection refused
    at redis.clients.jedis.Connection.connect(Connection.java:164)
    at redis.clients.jedis.BinaryClient.connect(BinaryClient.java:82)
    at redis.clients.jedis.BinaryJedis.connect(BinaryJedis.java:1641)
    at redis.clients.jedis.JedisFactory.makeObject(JedisFactory.java:85)
    at org.apache.commons.pool2.impl.GenericObjectPool.create(GenericObjectPool.java:868)
    at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:435)
    at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:363)
    at redis.clients.util.Pool.getResource(Pool.java:48)
    ... 48 more
Caused by: java.net.ConnectException: Connection refused
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at redis.clients.jedis.Connection.connect(Connection.java:158)
    ... 55 more
@WebIntegrationTest
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestAppConfig.class)
public class AuthenticationResourceTest {

  private RestTemplate restTemplate = new TestRestTemplate();

  @Test
  public void testUnauthenticated() {

    HttpHeaders headers = restTemplate.getForEntity("http://localhost:8080/api/session", String.class).getHeaders();

  }

}


@Configuration
@SpringBootApplication(exclude = {SessionAutoConfiguration.class, SessionRedisHttpConfiguration.class})
public class TestAppConfig {

  @Configuration
  static class SessionConfig extends BaseSessionConfig {

  }

}

共有1个答案

辛弘壮
2023-03-14

使用@ActiveProfiles测试注释来启用某些配置文件进行测试。如果不激活RedissessionConfig上定义的配置文件,就不应该加载该配置。

但也要确保RedisHttpSessionConfiguration不是通过自动配置加载的。

对评论的反应:

我不确定Redis是否有自动配置类。往春靴里看,它有。所以在测试过程中需要排除它。看看这个SO线程如何做到这一点。

 类似资料:
  • 问题内容: 当我运行单元测试时,它会调用我的计划任务。我想防止这种行为,这是由于我在主应用程序配置中遇到的事实造成的。 如何在单元测试中禁用此功能? 不知道我该怎么做?还是过度杀伤力?我当时在考虑为单元测试使用一个单独的AppConfiguration,但是当我这样做时,我感觉好像重复了两次代码吗? 单元测试示例。 问题答案: 如果你不想使用配置文件,则可以添加标志以启用/禁用应用程序调度 在你添

  • 问题内容: 我想为GUI编写测试用例。我想知道如何模拟JButton的单击,或者如何提取JTable的元素。 为此,我构建了一个简单的GUI,如果单击按钮并且JTextfield为空,则将计数增加1,但是如果提供了数字,则计数将被JTextfield中的整数代替。当然,我想使用Regex来确保输入到JTextfield中的文本实际上是整数,但是让我们假设用户不会四处乱逛并输入非整数。另外,当JTa

  • 以下测验提供了与JUnit Framework相关的多项选择题(MCQ)。 您必须阅读所有给定的答案并单击正确的答案。 如果您不确定答案,则可以使用“ Show Answer按钮Show Answer 。 您可以使用“ Next Quiz按钮在Next Quiz中检查新的问题集。 问题1 - 关于JUnit,以下哪项是正确的? A - JUnit测试可以组织成包含测试用例甚至其他测试套件的测试套件

  • 我正在使用Eclipse中的 JUnit5位于modul-path上,并且在module-info.Java中是必需的。 当我尝试运行代码时,总是会收到以下消息: 初始化引导层java.lang.module.findException时出错:无法为C:\users\tim hp.p2\pool\plugins\org.junit.jupiter.migrationsupport_5.0.0.v2

  • 我正在学习JUnit测试。我想在JUnit中测试getter和setter,但它不起作用。这是第一节课。 我需要如何更改以测试setter?我如何测试它?

  • 环境:Linux, Eclipse Juno,Java7, JUnit 当一个简单的应用程序(带有main方法的java类)在调试模式下运行时,“Drop to Frame”功能在Eclipse中运行良好。然而,如果从junit测试用例调用相同的方法,Eclipse中的“Drop to Frame”功能将被禁用。从文件中 注意:仅当当前VM支持drop to frame且所选stackframe不