I have a spring boot application where I have enabled mongo auditing. The application starts fine and stores mongo documents with all auditing fields (createdDate, updatedDate, etc.). However, when running unit test I get the following exception:
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoAuditingHandler': Cannot create inner bean '(inner bean)#115c946b' of type [org.springframework.data.mongodb.config.MongoAuditingRegistrar$MongoMappingContextLookup] while setting constructor argument; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name '(inner bean)#115c946b': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.mongodb.core.convert.MappingMongoConverter' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name '(inner bean)#115c946b': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.mongodb.core.convert.MappingMongoConverter' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.mongodb.core.convert.MappingMongoConverter' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Here is my main class
#SpringBootApplication
#EnableMongoAuditing
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(PatientstoreApplication.class, args);
}
}
And here is my test class:
#WebMvcTest(TestController.class)
public class TestTest {
#Autowired MockMvc mockMvc;
#MockBean TestService testService;
#Test
public void test() {
}
}
A reproducible example can be found here: https://github.com/jota87r/testapp
My question is: is there any configuration missing? should I manually create a bean of type for MappingMongoConverter for my test cases?
You can mock the MappingMongoConverter.class.
So your test class should be as follows:
#WebMvcTest(TestController.class)
public class TestTest {
#Autowired
MockMvc mockMvc;
#MockBean
TestService testService;
//Mock MappingMongoConverter
#MockBean
private MappingMongoConverter mappingMongoConverter;
#Test
public void test() {
}
I encountered the same situation.
In your #WebMvcTest class, try to add a test configuration like:
#TestConfiguration
static class TestConfig {
#Bean
public MappingMongoConverter mongoConverter() {
return new MappingMongoConverter(mock(DbRefResolver.class), mock(MappingContext.class));
}
}
Related
I'm having a trouble while configuring Spring AOP.
I created an aspect class which is below:
#Slf4j
#Aspect
#RequiredArgsConstructor
#Component
public class LoggingAspect {
private static final Logger logger = CommonLogger.getLogger(LoggingAspect.class);
private final ObjectMapper mapper;
private final JobExecutionService jobExecutionService;
}
Then I added a configuration file:
#Configuration
#EnableAspectJAutoProxy(proxyTargetClass = true)
#RequiredArgsConstructor
public class AspectConfiguration {
private final ObjectMapper objectMapper;
private final JobExecutionService jobExecutionService;
#Bean
public LoggingAspect loggingAspect() {
return new LoggingAspect(objectMapper, jobExecutionService);
}
}
But when I started the application, I am getting below errors:
Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.context.support.ClassPathXmlApplicationContext]: Constructor threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'aspectConfiguration' defined in URL: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.fasterxml.jackson.databind.ObjectMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
I have added aspectjrt and aspectjweaver dependencies to pom.xml.
Spring version is 4.3.6
I couldn't figure out where the problem is. Any help would be appreciated.
Add class:
#Configuration
public class BeanConfig {
#Bean
public ObjectMapper objectMapper() {
return new ObjectMapper();
}
}
this is my step definition class,
#ContextConfiguration("classpath*:/applicationContext.xml")
public class Setup {
#Autowired
SetupPageObjects setupPageObjects;
#Autowired
private setUp_Helper dataHelper;
#When("xxxxx")
public void public void user_navigates_to_setup_page() {
}
}
class:
#Component
public class SetupPageObjects extends TestCoordinator {
codes()
}
Runner class:
#RunWith(Cucumber.class)
#CucumberOptions(tags = "#Varun",
features = "features",
glue = "gluepath",
monochrome = true
)
#ContextConfiguration("classpath*:/applicationContext.xml")
public class CucumnerContinousITSuite {
}
Error:
cucumber.runtime.CucumberException: Error creating bean with name 'com.application.test.cucumberIntegrationTest.stepdefenitions.Setup': Unsatisfied dependency expressed through field 'SetupPageObjects'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.application.test.cucumberIntegrationTest.pageobjectrepository.SetupPageObjects' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Hi I am using MongoDB transaction feature with Spring Boot 2.3.5.RELEASE version. I am getting the following exception. I am writing the integration test with the controller classes.
Exception given below.
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.app.cat.resource.Test0': Unsatisfied dependency expressed through field 'controller'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.dell.pde.resources.NVTValidationCategoryController' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:643) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:130) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPost
I provide below the code snippet.
#Profile("test")
#ActiveProfiles("test")
#DataMongoTest(excludeAutoConfiguration = MongoDBTxnConfiguration.class)
#Import(TestMongoConfig1.class)
#EnableAutoConfiguration(exclude={ SecurityAutoConfiguration.class, DataSourceAutoConfiguration.class, RedisAutoConfiguration.class,
RedisRepositoriesAutoConfiguration.class,
SecurityFilterAutoConfiguration.class, SecurityAutoConfiguration.class })
#SpringBootApplication(scanBasePackages = {"com.app.cat"})
public class Test0 {
#Autowired
private CategoryController controller;
#Autowired
#Qualifier("validations")
private ValidationService vldnService;
#Test
void testAllValidationsBeforeEntry() {
System.out.println("controller : " + vldnService);
assertEquals(true, true);
}
}
Please guide me what I am doing wrong. Please help me.
#DataMongoTest annotation also uses #AutoConfigureDataMongo, #ImportAutoConfiguration. If you provide autoconfigured classes, it will conflict. You have to use #DataMongoTest to exclude other classes to load and run. Since it is a Test class, do not use #SpringBootApplication(scanBasePackages = {"com.app.cat"}). Finally I provide the bit code snippet which may be helpful to you.
#DataMongoTest(excludeAutoConfiguration = {SecurityAutoConfiguration.class,
SecurityFilterAutoConfiguration.class,
SecurityAutoConfiguration.class, ... <any other configuration>})
#Profile("test")
#ComponentScan(basePackages = {"com.app.cat"}, excludeFilters={
#ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE,
value= {MongoDBTxnConfiguration.class,SecurityCloudConfig.class})})
public class Test {
#Autowired
private YourControler ctrlr;
#Test
void test1() {
// Logic for testing
}
}
I'm getting this error while trying to start my app. I've looked at many similar problems and topics but none seems to help me.
Error creating bean with name 'databaseManager': Unsatisfied dependency
expressed through field 'articleRepo'; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'pl.dzejkobdevelopment.database.repositories.ArticleRepo' available:
expected at least 1 bean which qualifies as autowire candidate. Dependency
annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
#Repository
public interface ArticleRepo extends CrudRepository<Article, Long> {
}
and...
#Service
public class DatabaseManager {
#Autowired
private ArticleRepo articleRepo;
#Autowired
private CommentRepo commentRepo;
#Autowired
private TagRepo tagRepo;
#Autowired
private UserRepo userRepo;
public void addArticle(Article article){
article.getTags().forEach(tag ->addTag(tag));
articleRepo.save(article);
}
public List<Comment> findComments(User user){
return commentRepo.findByCommentAuthor(user);
}
private void addTag(Tag tag){
tagRepo.save(tag);
}
}
and...
#Configuration
//#ComponentScan(basePackages="pl.dzejkobdevelopment.database.repositories")
public class AppConfig {
#Bean
public WebsiteProporties websiteProporties(){
return new WebsiteProporties();
}
#Bean
public StorageProperties storageProporties(){ return new StorageProperties();}
#Bean
public DatabaseManager databaseManager(){ return new DatabaseManager();}
}
}
Uncommenting ComponentScan doesn't help.
EDIT
Changeing ComponentScan for EnableJpaRepositories gives this error:
Error creating bean with name 'databaseManager': Unsatisfied dependency expressed through field 'articleRepo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'articleRepo': Cannot create inner bean '(inner bean)#14a1d6d' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#14a1d6d': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
Try to use
#EnableJpaRepositories("pl.dzejkobdevelopment.database.repositories")
instead of ComponentScan.
I try to add third-party bean to my application:
#Configuration
#ComponentScan(...)
public class ApplicationConfiguration {
#Bean(name = "mqSocket")
public ZMQ.Socket startServer() {
try (ZMQ.Context ctx = ZMQ.context(1);
ZMQ.Socket publisher = ctx.socket(ZMQ.PUB)) {
publisher.bind("tcp://*:5556");
return publisher;
}
}
}
and I try to autowire this like this:
#RestController
public class MyRestController {
#Autowired
private ZMQ.Socket mqSocket;
but it prints following:
java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myRestController': Unsatisfied dependency expressed through field 'mqSocket'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.zeromq.ZMQ$Socket' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
...
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.zeromq.ZMQ$Socket' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
...
You should add the #Import annotation on your Application like class.
Eg.:
#Import(ApplicationConfiguration.class)
public class Application {
}
Note: cf. #M.Prokhorov comments, the ZMQ.Socket is closed by the try-with-resource statement
You created a bean with name mqSocket so I guess you have to use the #Qualifier annotation; try to change your code in this way:
#RestController
public class MyRestController {
#Autowired
#Qualifier("mqSocket")
private ZMQ.Socket mqSocket;
I hope it's usefull
Angelo