禁用 Spring Boot 启动器 Cassandra 进行单元测试

Posted

技术标签:

【中文标题】禁用 Spring Boot 启动器 Cassandra 进行单元测试【英文标题】:Disable spring boot starter Cassandra for unit testing 【发布时间】:2018-08-06 22:39:57 【问题描述】:

我需要在一个项目中使用 Cassandra,并且具有以下 gradle 依赖:

compile "org.springframework.boot:spring-boot-starter-data-cassandra"

问题在于,尽管 Cassandra AutoConfiguration 类被标记为从单元测试中排除,但不知何故 spring 仍然尝试实例化与此依赖关系相关的类。

这是我的单元测试:

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

@RunWith( SpringRunner.class )
@SpringBootTest
@AutoConfigureMockMvc
@EnableAutoConfiguration( exclude = 
        org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration.class,
        org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration.class
 )
public class HealthTest 

    @Autowired
    private MockMvc mockMvc;


    @Test
    public void contextLoads() 
        Assert.assertNotNull( mockMvc );
    

    @Test
    public void healthControllerIsUp() throws Exception 
        mockMvc.perform( MockMvcRequestBuilders.get( "/health" ) )
                .andExpect( MockMvcResultMatchers.status().isOk() );
    

这是我得到的错误,显然是因为 Spring 无法实例化 cluster 对象。

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.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189)
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    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:191)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cluster' defined in class path resource [org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.datastax.driver.core.Cluster]: Factory method 'cluster' threw exception; nested exception is java.lang.NoClassDefFoundError: com/google/common/util/concurrent/FutureFallback
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    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:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120)
    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.beans.BeanInstantiationException: Failed to instantiate [com.datastax.driver.core.Cluster]: Factory method 'cluster' threw exception; nested exception is java.lang.NoClassDefFoundError: com/google/common/util/concurrent/FutureFallback
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    ... 41 more
Caused by: java.lang.NoClassDefFoundError: com/google/common/util/concurrent/FutureFallback
    at org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration.cluster(CassandraAutoConfiguration.java:66)
    at org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration$$EnhancerBySpringCGLIB$$7c58ae77.CGLIB$cluster$0(<generated>)
    at org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration$$EnhancerBySpringCGLIB$$7c58ae77$$FastClassBySpringCGLIB$$fb4ab05b.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358)
    at org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration$$EnhancerBySpringCGLIB$$7c58ae77.cluster(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
    ... 42 more
Caused by: java.lang.ClassNotFoundException: com.google.common.util.concurrent.FutureFallback
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 53 more

查看CassandraAutoConfiguration类,该类注释如下:

@Configuration
@ConditionalOnClass( Cluster.class )
@EnableConfigurationProperties(CassandraProperties.class)
public class CassandraAutoConfiguration

我正在寻找一种简洁的方法来解决这个问题,而无需在每个与 Cassandra 无关的测试上配置 Cassandra。

【问题讨论】:

您似乎遇到了类路径问题,因为您的类路径上没有 Google Guava:ClassNotFoundException: com.google.common.util.concurrent.FutureFallback How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?的可能重复 【参考方案1】:

这不是很优雅,但可以用于单元测试:

@MockBean CassandraDataAutoConfiguration configuration;
@MockBean CassandraCustomConversions conversions;
@MockBean SessionFactory sessionFactory;
@MockBean CassandraReactiveDataAutoConfiguration reactiveCassandraSession;
@MockBean CassandraAutoConfiguration cassandraAutoConfiguration;
@MockBean CqlSessionBuilder cqlSessionBuilder;
@MockBean CqlSession cqlSession;

【讨论】:

以上是关于禁用 Spring Boot 启动器 Cassandra 进行单元测试的主要内容,如果未能解决你的问题,请参考以下文章

Spring boot - 在启动时禁用 Liquibase

Spring Boot:如何禁用 Tomcat 启动日志记录?

关于spring boot如何正确禁用web环境

在spring boot / spring data elasticsearch中禁用自动索引创建

如何在使用 Spring Boot 的 JWT 令牌时禁用同一用户帐户的多个登录

Spring Boot新模块devtools