英文:
How to do integration testing using Fongo (Fake mongo) in Spring Boot
问题
I see that you have provided a detailed error message related to your Spring Boot application with MongoDB integration testing using Fongo. However, it's a complex issue that may require in-depth analysis of your code and configuration. Here are some steps you can take to resolve the issue:
-
Check Dependencies: Ensure that your project's dependencies, including Spring Boot, MongoDB, and Fongo, are correctly configured in your
pom.xml
(if you are using Maven) orbuild.gradle
(if you are using Gradle). Make sure you have the correct versions of these dependencies. -
Check MongoDB Configuration: Verify your MongoDB configuration in
MongoConfig.java
to ensure it's correctly configured. Pay attention to the properties such as the database name, host, and port. Also, ensure that the MongoDB server is running. -
Check Application Properties: Review your
application.properties
orapplication.yml
file to ensure that the MongoDB-related properties are correctly set. Verify the database name and other MongoDB related configurations. -
Check Spring Profiles: If you are using different Spring profiles for testing, development, and production, ensure that the correct profile is activated during your integration tests. You can set the active profile using the
@ActiveProfiles
annotation on your test class. -
Check Bean Configuration: Review your bean configurations, particularly in
MongoConfig.java
. Ensure that theMongoTemplate
,MongoDbFactory
, andMongoClient
beans are defined correctly. -
Check Fongo Configuration: Double-check your Fongo configuration in
AbstractFongoBaseConfiguration.java
. Make sure it correctly overrides the MongoDB configuration when running tests. -
Check Component Scanning: Verify that component scanning is correctly configured, especially in
ConfigServerWithFongoConfiguration.java
. Ensure that the packages are scanned correctly. -
Check for Circular Dependencies: Circular dependencies can sometimes lead to such issues. Ensure that your beans and dependencies are correctly structured and do not result in circular dependencies.
-
Check SSL Configuration: If your application uses SSL, ensure that the SSL keystore file and password are correctly set in your
application.properties
orapplication.yml
file. -
Check for Null Pointers: The error message indicates a
NullPointerException
. Carefully review your code, especially inMongoConfig.java
andAbstractFongoBaseConfiguration.java
, to find potential null pointer issues. -
Log Configuration: Review your application's log configuration to see if there are any additional error messages or warnings that can provide more context.
-
Debugging: Use debugging tools provided by your IDE to step through your code during integration tests. This can help identify the specific point where the issue occurs.
-
Consult Documentation: Refer to the documentation of the libraries and frameworks you are using (Spring Boot, MongoDB, Fongo) for any known issues or configuration details specific to integration testing.
Without access to your entire codebase and environment, it's challenging to pinpoint the exact cause of the issue. I recommend systematically going through the above steps to identify and resolve the problem. If you still encounter issues, consider seeking help from your development team or a community forum related to Spring Boot and MongoDB integration.
英文:
I am working on spring boot application with mongodb as backend.
mongorepository for crud operation
I want to do integration testing using fake mongo (fongo)
I have taken reference from following link to do integration testing using fongo but no luck.
https://www.paradigmadigital.com/dev/tests-integrados-spring-boot-fongo/
INTEGRATION test is trying to connect to real database and IT fails
@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");
}
}
I am getting following error while executing Integration test
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
My main 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 {
}
Could you please suggest , what needs to be done to resolve this issue ?
答案1
得分: 1
但是对于 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;
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
和 AbstractFongoBaseConfiguration
与 Test 目录下的 PersonControllerITest
类位于相同的包中。
我还假设你的应用程序正常运行,只有在集成测试中遇到问题。
英文:
I had tried with your code for Integration Test and Same config file.
But for AbstractFongoBaseConfiguration.class
i had provided below code.
I had removed that @EnableAutoConfiguration(exclude={MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
line. It's working fine for me.
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 I had attached video with same code.
Also one point i want to inform you both make your ConfigServerWithFongoConfiguration
and AbstractFongoBaseConfiguration
are with same package of Test directory as PersonControllerITest
class.
I had also pre-assumed that your application run fine and you only have problem with Integration Test.
Here i had attached successfully run test case screen as well.
答案2
得分: 0
Fongo似乎不再维护。如果可行的话,我会转换到Test Containers https://www.testcontainers.org/modules/databases/mongodb/
这是一个更好的参考资料,适用于您尝试的内容:https://www.baeldung.com/spring-boot-embedded-mongodb
您需要在测试中添加@AutoConfigureDataMongo
。
英文:
Fongo doesn't seem to be maintained anymore. I would switch to Test Containers if feasible https://www.testcontainers.org/modules/databases/mongodb/
This is a better reference for what you are trying to do: https://www.baeldung.com/spring-boot-embedded-mongodb
You need to add @AutoConfigureDataMongo
on the test.
答案3
得分: -1
在您的堆栈跟踪中,异常发生在 "MongoConfig" 类中。
如下所示:
com.company.myapp.configs.MongoConfig.mongoClient(MongoConfig.java:78)
这向我表明您的Spring配置链未按照您打算的方式设置。看起来实际的 MongoConfig 类仍然在实际应用程序环境中被加载。
如果没有您的完整项目(或实际导致空指针异常的 Config 类),几乎不可能对您的问题提供详细答案。
然而,我建议您创建一个特定的 TestConfig Spring 配置类,以便只包括您想要包含在测试上下文中的主要配置类。
简而言之: 检查您的配置设置,找出为什么会加载 MongoConfig.java,如果它打算被加载,请在此处包括它,以便人们可以找出问题所在。
英文:
In your stacktrace, the exception occurs in the "MongoConfig" class.
As seen here:
com.company.myapp.configs.MongoConfig.mongoClient(MongoConfig.java:78)
It indicates to me that your Spring configuration chain is not set up as you intend it to be. It looks like the actual MongoConfig class intended to be used in the actual application environment is still being loaded.
Without having your full project (or the Config class that is actually causing the NullPointer), it is near impossible to give a detailed answer to your issue.
However, I would advise you to create a specific TestConfig spring configuration class, so you can include only the main config classes that you want to be part of your test context.
TLDR: take a look at your config set-up, and figure out why your MongoConfig.java is loaded. If it is intended to be loaded, include it here so people can figure out what the problem is.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论