如何在Spring Boot中使用FongoFake mongo进行集成测试

如何解决如何在Spring Boot中使用FongoFake mongo进行集成测试

我正在使用mongodb作为后端的Spring Boot应用程序。

用于操作的mongorepository

我想使用假mongo(fongo)进行集成测试

我已从以下链接中获取参考,以便使用fongo进行集成测试,但是没有运气。

https://www.paradigmadigital.com/dev/tests-integrados-spring-boot-fongo/

集成测试正在尝试连接到真实数据库并且IT失败

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = { ConfigServerWithFongoConfiguration.class },properties = {
        "server.port=8980" },webEnvironment = WebEnvironment.DEFINED_PORT)
@AutoConfigureMockMvc
@TestPropertySource(properties = { "spring.data.mongodb.database=test" })
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class PersonControllerITest {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private MockMvc mockMvc;

    private ObjectMapper jsonMapper;

    @Before
    public void setUp() {
        jsonMapper = new ObjectMapper();
    }

    @Test
    public void testGetPerson() throws Exception {

        Person personFongo = new Person();
        personFongo.setId(1);
        personFongo.setName("Name1");
        personFongo.setAddress("Address1");
        mongoTemplate.createCollection("person");
        mongoTemplate.insert(personFongo);

        ResultActions resultAction = mockMvc.perform(MockMvcRequestBuilders.get("http://localhost:8090/api/person/1"));
        resultAction.andExpect(MockMvcResultMatchers.status().is2xxSuccessful());
        MvcResult result = resultAction.andReturn();
        Person personResponse = jsonMapper.readValue(result.getResponse().getContentAsString(),Person.class);
        Assert.assertEquals(1,personResponse.getId());
        Assert.assertEquals("Name1",personResponse.getName());
        Assert.assertEquals("Address1",personResponse.getAddress());

    }

    @Test
    public void testCreatePerson() throws Exception {

        Person personRequest = new Person();
        personRequest.setId(1);
        personRequest.setName("Name1");
        personRequest.setAddress("Address1");

        String body = jsonMapper.writeValueAsString(personRequest);

        ResultActions resultAction = mockMvc.perform(MockMvcRequestBuilders.post("http://localhost:8090/api/person")
                .contentType(MediaType.APPLICATION_JSON).content(body));
        resultAction.andExpect(MockMvcResultMatchers.status().isCreated());

        Person personFongo = mongoTemplate.findOne(new Query(Criteria.where("id").is(1)),Person.class);
        Assert.assertEquals(personFongo.getName(),"Name1");
        Assert.assertEquals(personFongo.getAddress(),"Address1");
    }
}

执行集成测试时出现以下错误

   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.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:44)
        at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
    
    Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityConfig': Unsatisfied dependency expressed through field 'entitlementsRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entitlementsRepository': Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoTemplate' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDbFactory' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoClient' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.MongoClient]: Factory method 'mongoClient' threw exception; nested exception is java.lang.NullPointerException
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
        at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
        ... 25 more
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entitlementsRepository': Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoTemplate' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDbFactory' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoClient' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.MongoClient]: Factory method 'mongoClient' threw exception; nested exception is java.lang.NullPointerException
        at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
        at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1531)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1276)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
        
        ... 44 more
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoTemplate' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDbFactory' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoClient' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.MongoClient]: Factory method 'mongoClient' threw exception; nested exception is java.lang.NullPointerException
        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)
        
        ... 57 more
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDbFactory' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoClient' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.MongoClient]: Factory method 'mongoClient' threw exception; nested exception is java.lang.NullPointerException
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
        ... 66 more
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDbFactory' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoClient' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.MongoClient]: Factory method 'mongoClient' threw exception; nested exception is java.lang.NullPointerException
        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)
        
        ... 67 more
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoClient' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.MongoClient]: Factory method 'mongoClient' threw exception; nested exception is java.lang.NullPointerException
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
        ... 89 more
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoClient' defined in class path resource [com/company/myapp/configs/MongoConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.MongoClient]: Factory method 'mongoClient' threw exception; nested exception is java.lang.NullPointerException
        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.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.obtainBeanInstanceFromFactory(ConfigurationClassEnhancer.java:389)
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:361)
        at com.company.myapp.configs.MongoConfig$$EnhancerBySpringCGLIB$$33034a08.mongoClient(<generated>)
        at com.company.myapp.configs.MongoConfig.mongoDbFactory(MongoConfig.java:73)
        at com.company.myapp.configs.MongoConfig$$EnhancerBySpringCGLIB$$33034a08.CGLIB$mongoDbFactory$1(<generated>)
        at com.company.myapp.configs.MongoConfig$$EnhancerBySpringCGLIB$$33034a08$$FastClassBySpringCGLIB$$50ee8948.invoke(<generated>)
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358)
        at com.company.myapp.configs.MongoConfig$$EnhancerBySpringCGLIB$$33034a08.mongoDbFactory(<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)
        ... 90 more
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.MongoClient]: Factory method 'mongoClient' threw exception; nested exception is java.lang.NullPointerException
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
        ... 112 more
    Caused by: java.lang.NullPointerException
        at java.util.Hashtable.put(Hashtable.java:460)
        at java.util.Properties.setProperty(Properties.java:166)
        at java.lang.System.setProperty(System.java:796)
        at com.company.myapp.configs.MongoConfig.mongoClient(MongoConfig.java:78)
        at com.company.myapp.configs.MongoConfig$$EnhancerBySpringCGLIB$$33034a08.CGLIB$mongoClient$3(<generated>)
        at com.company.myapp.configs.MongoConfig$$EnhancerBySpringCGLIB$$33034a08$$FastClassBySpringCGLIB$$50ee8948.invoke(<generated>)
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358)
        at com.company.myapp.configs.MongoConfig$$EnhancerBySpringCGLIB$$33034a08.mongoClient(<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)
        ... 113 more

我的主要Application.java

@SpringBootApplication(exclude = {MongoDataAutoConfiguration.class,MongoAutoConfiguration.class})
@EntityScan(basePackageClasses = Jsr310Converters.class)
@ComponentScan(basePackages = {"com.company.myapp","com.company.myapp.repository"})
@AutoConfigureAfter(MongoConfig.class)
@EnableSwagger2
@EnableScheduling
public class Application
{
public class Application
{
    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    @Value("${http.port}")
    int httpPort;

    @Value("${ssl.port}")
    int sslPort;

    @Value("${ssl.keystore.file}")
    String keyStoreFile;

    @Value("${ssl.keystore.password}")
    String keyStorePassword;

    @Autowired
    FileUtil fileUtil;

    public static void main(String[] args)
    {
        Runtime.getRuntime().addShutdownHook(new Thread() {                       
            @Override
            public void run() {
                logger.info("myapp server shutdown initiated");
                LogManager.shutdown();
                logger.info("myapp server shutdown completed");
            }
        });
        SpringApplication.run(Application.class,args);                          
    }

    @Bean
    public CompressingFilter compressingFilter()
    {
        return new CompressingFilter();
    }

    @Bean
    public EmbeddedServletContainerFactory servletContainer()
    {
        String keystore = "dev";

        TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
        tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) con -> {
                    //if ("true".equalsIgnoreCase(sslEnabled)) {
                    logger.info("----------------------------------------- Initialising ssl endpoint -------------------------------------");
                    Http11NioProtocol proto = (Http11NioProtocol) con.getProtocolHandler();
                    proto.setSSLEnabled(true);
                    con.setScheme("https");
                    con.setSecure(true);
                    con.setPort(sslPort);
                    proto.setKeystoreFile(fileUtil.getConfigFilePath(keyStoreFile));
                    proto.setKeystorePass(keystore);
                    proto.setKeyPass(keystore);
                    logger.info("---------------------------------------- Initialised ssl endpoint ----------------------------------------");
                    //}
                });

        tomcat.addAdditionalTomcatConnectors(createStandardConnector());
        return tomcat;
    }

    private Connector createStandardConnector()
    {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setPort(httpPort);
        return connector;
    }
}

AbstractFongoBaseConfiguration.java

@EnableAutoConfiguration(exclude={MongoAutoConfiguration.class,MongoDataAutoConfiguration.class})
public abstract class AbstractFongoBaseConfiguration extends AbstractMongoConfiguration{

    @Autowired
    private Environment env;

    @Override
    protected String getDatabaseName() {
        return env.getRequiredProperty("spring.data.mongodb.database");
    }

    @Override
    public Mongo mongo() throws Exception {
        return new Fongo(getDatabaseName()).getMongo();
    }
}

ConfigServerWithFongoConfiguration.java

@EnableAutoConfiguration(exclude = { EmbeddedMongoAutoConfiguration.class,MongoAutoConfiguration.class,MongoDataAutoConfiguration.class })
@Configuration
@ComponentScan(basePackages = { "com.company.myapp" },excludeFilters = {
        @ComponentScan.Filter(classes = { SpringBootApplication.class }) })
public class ConfigServerWithFongoConfiguration extends AbstractFongoBaseConfiguration {

}

请问您可以提出什么解决方案?

解决方法

我已经尝试过使用您的集成测试和相同配置文件的代码。

但是对于 AbstractFongoBaseConfiguration.class ,我提供了以下代码。

我已删除了该 @EnableAutoConfiguration(exclude={MongoAutoConfiguration.class,MongoDataAutoConfiguration.class}) 行。对我来说很好。

package com.company.myapp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;

import com.github.fakemongo.Fongo;
import com.mongodb.Mongo;
//this exclude i had removed
public abstract class AbstractFongoBaseConfiguration extends AbstractMongoConfiguration{

    @Autowired
    private Environment env;

    @Override
    protected String getDatabaseName() {
        return env.getRequiredProperty("spring.data.mongodb.database");
    }

    @Override
    public Mongo mongo() throws Exception {
        return new Fongo(getDatabaseName()).getMongo();
    }
}

Here我已经用相同的代码附加了视频。

还有一点我想通知您,使您的 ConfigServerWithFongoConfiguration AbstractFongoBaseConfiguration 都与 PersonControllerITest 类。

我还预先假设您的应用程序可以正常运行,而您仅遇到集成测试问题。

这里我还附加了成功运行测试用例的屏幕。enter image description here

,

Fongo似乎不再被维护。如果可行,我会切换到“测试容器” https://www.testcontainers.org/modules/databases/mongodb/

这是您尝试做的更好的参考:https://www.baeldung.com/spring-boot-embedded-mongodb

您需要在测试中添加@AutoConfigureDataMongo

,

在您的堆栈跟踪中,异常发生在“ MongoConfig”类中。 如此处所示:

com.company.myapp.configs.MongoConfig.mongoClient(MongoConfig.java:78)

这向我表明您的Spring配置链未按您的预期进行设置。似乎仍在加载要在实际应用程序环境中使用的实际MongoConfig类。

没有完整的项目(或实际上导致NullPointer的Config类),几乎不可能给出问题的详细答案。 但是,我建议您创建一个特定的TestConfig弹簧配置类,以便仅包含要成为测试上下文一部分的主要配置类。

TLDR::查看您的配置设置,并弄清楚为什么加载MongoConfig.java。如果打算将其加载,请在此处包括它,以便人们找出问题所在。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-