We are trying to run a spring batch which is failing with below issue.
My configs :
1) Spring boot
#ComponentScan(basePackages = { "some pkgs” })
#ImportResource("classpath:dataSource.xml")
#EnableAutoConfiguration(exclude = DataSourceTransactionManager.class)
public class CollateralReportGeneratorBootstrapper {
public static void main(String[] args) {
System.exit(SpringApplication.exit(SpringApplication.run(CollateralReportGeneratorBootstrapper.class, args)));
}
}
2) Batch
#Configuration
#EnableBatchProcessing
#ComponentScan(basePackages = { "some pkgs”})
public class ReportGenerator {
#Autowired
private JobBuilderFactory jobBuilderFactory;
#Autowired
private StepBuilderFactory stepBuilderFactory;
3) Dependencies : spring-batch-core, spring-batch-infrastructure, spring-boot-starter-batch
Please let me know if someone faced this issue or any idea about possible solutions !!
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'jobLauncherCommandLineRunner' defined in class path resource [org/springframework/boot/autoconfigure/batch/BatchAutoConfiguration.class]: Unsatisfied dependency expressed through constructor argument with index 1 of type [org.springframework.batch.core.explore.JobExplorer]: : No qualifying bean of type [org.springframework.batch.core.explore.JobExplorer] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.batch.core.explore.JobExplorer] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:747)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:462)
I would suggest start with following sample and add your launcher class to it...
http://spring.io/guides/gs/batch-processing/
Related
I have updated SpringBoot version from 2.1.6 to 2.6.6 and after starting integration tests with testcontainers I am receiving below errors:
First error is:
13:25:08.793 [main] ERROR o.s.boot.SpringApplication - Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'approvalResource': Unsatisfied dependency expressed through field 'queryApprovals'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'queryApprovals': Unsatisfied dependency expressed through field 'approvalRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'approvalRepository' defined in adapters.outbound.repositories.ApprovalRepository defined in #EnableMongoRepositories declared on Licenses: Cannot create inner bean '(inner bean)#66589252' of type [org.springframework.data.repository.core.support.RepositoryFragmentsFactoryBean] while setting bean property 'repositoryFragments'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#66589252': Invocation of init method failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'squealRepositoryImplFragment': Cannot resolve reference to bean 'squealRepositoryImpl' while setting constructor argument; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'squealRepositoryImpl': Unsatisfied dependency expressed through field 'mongoTemplate'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mongoTemplate' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryDependentConfiguration.class]: Unsatisfied dependency expressed through method 'mongoTemplate' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mongoDatabaseFactory' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryConfiguration.class]: Unsatisfied dependency expressed through method 'mongoDatabaseFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongo' defined in class path resource [org/springframework/boot/autoconfigure/mongo/MongoAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.client.MongoClient]: Factory method 'mongo' threw exception; nested exception is java.lang.IllegalStateException: Invalid mongo configuration, either uri or host/port/credentials/replicaSet must be specified
then:
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mongoDatabaseFactory' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryConfiguration.class]: Unsatisfied dependency expressed through method 'mongoDatabaseFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongo' defined in class path resource [org/springframework/boot/autoconfigure/mongo/MongoAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.client.MongoClient]: Factory method 'mongo' threw exception; nested exception is java.lang.IllegalStateException: Invalid mongo configuration, either uri or host/port/credentials/replicaSet must be specified
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:541)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1352)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1195)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1389)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1309)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:887)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791)
... 169 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongo' defined in class path resource [org/springframework/boot/autoconfigure/mongo/MongoAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.client.MongoClient]: Factory method 'mongo' threw exception; nested exception is java.lang.IllegalStateException: Invalid mongo configuration, either uri or host/port/credentials/replicaSet must be specified
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:658)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:638)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1352)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1195)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1389)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1309)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:887)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791)
... 183 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.client.MongoClient]: Factory method 'mongo' threw exception; nested exception is java.lang.IllegalStateException: Invalid mongo configuration, either uri or host/port/credentials/replicaSet must be specified
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653)
... 197 common frames omitted
Caused by: java.lang.IllegalStateException: Invalid mongo configuration, either uri or host/port/credentials/replicaSet must be specified
at org.springframework.util.Assert.state(Assert.java:76)
at org.springframework.boot.autoconfigure.mongo.MongoPropertiesClientSettingsBuilderCustomizer.validateConfiguration(MongoPropertiesClientSettingsBuilderCustomizer.java:61)
at org.springframework.boot.autoconfigure.mongo.MongoPropertiesClientSettingsBuilderCustomizer.customize(MongoPropertiesClientSettingsBuilderCustomizer.java:52)
at org.springframework.boot.autoconfigure.mongo.MongoClientFactorySupport.customize(MongoClientFactorySupport.java:55)
at org.springframework.boot.autoconfigure.mongo.MongoClientFactorySupport.createMongoClient(MongoClientFactorySupport.java:49)
at org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration.mongo(MongoAutoConfiguration.java:55)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
... 198 common frames omitted
Initializer class:
#Slf4j
public class IntegrationTestContextInitializer implements
ApplicationContextInitializer<ConfigurableApplicationContext> {
private static final MongoDBContainer mongoDbContainer = new MongoDBContainer(DockerImageName.parse("mongo:4.0.18-xenial")).withReuse(true);
private static final KeycloakContainer keycloakContainer = new KeycloakContainer("jboss/keycloak:12.0.4")
.withRealmImportFile("test-realm.json")
.withAdminUsername("admin")
.withAdminPassword("password")
.withReuse(true)
.withStartupTimeout(Duration.ofMinutes(5));
private static final GenericContainer<?> mailContainer = new GenericContainer<>(DockerImageName.parse("reachfive/fake-smtp-server:0.8.1")).withReuse(true).withExposedPorts(1025);
static {
mailContainer.start();
mongoDbContainer.start();
keycloakContainer.start();
}
#Override
public void initialize(#NotNull ConfigurableApplicationContext configurableApplicationContext) {
log.info("MongoDB URI: {}", mongoDbContainer.getReplicaSetUrl());
log.info("Keycloak URI: {}", keycloakContainer.getAuthServerUrl());
log.info("Mail server Port: {}", mailContainer.getMappedPort(1025));
TestPropertyValues values = TestPropertyValues.of(
"spring.data.mongodb.uri=" + mongoDbContainer.getReplicaSetUrl(),
"de.easy.myeasy.licenses.keycloak.username=" + keycloakContainer.getAdminUsername(),
"de.easy.myeasy.licenses.keycloak.password=" + keycloakContainer.getAdminPassword(),
"keycloak.auth-server-url=" + keycloakContainer.getAuthServerUrl(),
"spring.mail.host=" + mailContainer.getHost(),
"spring.mail.port=" + mailContainer.getMappedPort(1025),
"spring.mail.properties.mail.smtp.auth=false",
"spring.mail.properties.mail.smtp.starttls.enable=false"
);
values.applyTo(configurableApplicationContext);
}
}
BaseIT class:
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#AutoConfigureMockMvc
#ActiveProfiles("test")
#Slf4j
#ContextConfiguration(initializers = IntegrationTestContextInitializer.class)
public class BaseIntegrationTest {
#Autowired
protected ObjectMapper objectMapper;
#Autowired
protected MockMvc mockMvc;
#Autowired
protected MongoTemplate mongoTemplate;
#Autowired
protected WebApplicationContext webApplicationContext;
#SuppressWarnings("unused")
#Autowired
private KeycloakService keycloakService;
#Autowired
private KeycloakUserAdminService keycloakUserAdminService;
#Autowired
private UserRepository userRepository;
#Autowired
private QueryProducts queryProducts;
private final String[] downloadWhitelist = {"bit.ly", "downloads.com", "updatedlink.com", "newsownloadlink.com"};
#BeforeEach
public void setup() throws UserServiceException {
log.info("--------- Integration Test Starting ---------");
ReflectionTestUtils.setField(queryProducts, "downloadWhitelist", downloadWhitelist);
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
seedIntegrationTestUsers();
}
private void removeUser(String name){
try{
keycloakUserAdminService.deleteUser(name);
} catch (UserServiceException e) {
log.debug("Delete {} failed", name,e);
}
}
#AfterEach
public void tearDown() {
Stream<String> collectionNames = mongoTemplate.getCollectionNames().stream().filter(cName -> !cName.startsWith("system"));
collectionNames.forEach(cName -> mongoTemplate.findAllAndRemove(new Query(), cName));
removeUser("it_tester#tester.com");
removeUser("it_tester2#tester.com");
removeUser("it_tester3#customera.com");
log.info("--------- Integration Test Stopped ---------");
}
public void seedIntegrationTestUsers() throws UserServiceException {
userRepository.save(User.builder().username("it_tester#tester.com").email("it_tester#tester.com").build());
userRepository.save(User.builder().username("it_tester2#tester.com").email("it_tester2#tester.com").build());
KeycloakUser keycloakUser = new KeycloakUser();
keycloakUser.setUsername("it_tester#tester.com");
keycloakUser.setEmail("it_tester#tester.com");
keycloakUser.setFirstName("tester");
keycloakUser.setLastName("tester");
keycloakUser.setEnabled(true);
KeycloakUser keycloakUser2 = new KeycloakUser();
keycloakUser2.setUsername("it_tester2#tester.com");
keycloakUser2.setEmail("it_tester2#tester.com");
keycloakUser2.setFirstName("tester2");
keycloakUser2.setLastName("tester2");
keycloakUser2.setEnabled(true);
KeycloakUser keycloakUser3 = new KeycloakUser();
keycloakUser3.setUsername("it_tester3#customera.com");
keycloakUser3.setEmail("it_tester3#customera.com");
keycloakUser3.setFirstName("tester3");
keycloakUser3.setLastName("tester3");
keycloakUser3.setEnabled(true);
keycloakUserAdminService.createUser(keycloakUser);
keycloakUserAdminService.createUser(keycloakUser2);
keycloakUserAdminService.createUser(keycloakUser3);
}
}
Test class for loading context:
public class ContextLoadIntegrationTest extends BaseIntegrationTest{
#Test
void contextLoads() {
System.out.println("Context loads!");
}
}
Moreover I have #EnableMongoRepositories annotation in Application:
#SpringBootApplication
#EnableMongoRepositories(basePackages = {"adapters.outbound.repositories", "ps.squeal"})
public class MyApplication {
public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException {
SpringApplication.run(MyApplication.class, args);
}
}
It is working with Spring boot 2.1.6 but after migrating to 2.6.6 it is throwing errors. What is missing here to make it work? I am using JUnit5.
I have commented spring.data.mongodb.* in all properties files and it worked.
Looks like Spring was not using test profile as stated in #ActiveProfiles("test") annotation.
Once I run my code it gives below error. Howenter image description here I can solve it.
Field personRepository in com.example.demo.service.PersonService required a bean named 'mongoTemplate' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean named 'mongoTemplate' in your configuration.
You need to explicitly register bean to spring container.
#Configuration public class AppConfig {
public #Bean MongoClient mongoClient() {
return new MongoClient("localhost"); }
public #Bean MongoTemplate mongoTemplate() {
return new MongoTemplate(mongoClient(), "mydatabase");
} }
I am trying to test my #Service with the actual object of Spring Data Repository, where I am trying to use in memory database.I am using below annotation in my unit test.
#ActiveProfiles("test")
#RunWith(SpringRunner.class)
#EnableJpaRepositories
#SpringBootTest(classes = {MyService.class})
public class T24PortfolioRequestHandlerTest {
#Autowired
private MyService myService;
#Autowired
private MyRepository myRepository;
#Test
public void handleRequest() {
String output = myService.handleRequest(testData, "123", "TEST");
Assert.assertNotNull(output);
Assert.assertEquals("TESTING", output);
}
}
I am getting below exception while running the test.
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.....respository.MyRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
If I specify MyRepository.class in SpringBootConfiguratio(classes={MyService.class, MyRepository.class}) I am getting below error.
org.springframework.beans.BeanInstantiationException: Failed to instantiate [...respository.MyRepository]: Specified class is an interface
Is there any another way to tell spring boot about my repositories?
I Have an Spring Boot Application (1.5.10.RELEASE) which contains a main (SpringBootApplication) like this:
#SpringBootApplication
#Configuration
#EntityScan(basePackages = { "db.modell", "db.modell.base" })
#ComponentScan(basePackages = { "de.gui.test" })
public class SpringBootConsoleApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(SpringBootConsoleApplication.class, args);
}
}
and two REST controllers like the following:
#RestController
#RequestMapping("/as")
public class AController {
#Autowired
private ARepository aRepository;
#RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Collection<A>> getAs() {
return new ResponseEntity<>(orgtFarbeRepository.findAll(), HttpStatus.OK);
}
#RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<A> getA(#PathVariable long id) {
A a = ARepository.findOne(id);
if (party != null) {
return new ResponseEntity<>(ARepository.findOne(id), HttpStatus.OK);
} else {
return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
}
}
}
Furthermore I have a single test like this:
#RunWith(SpringRunner.class)
#WebMvcTest(AController.class)
public class AControllerTest {
#Autowired
private MockMvc mvc;
#MockBean
private ARepository ARepository;
#Test
public void firstTest() throws Exception {
A a = new aFarbe();
a.set....
when(ARepository.findAll()).thenReturn(Collections.singleton(a));
mvc.perform(
get("/as")
.accept(MediaType.APPLICATION_JSON_UTF8_VALUE)
)
.andExpect(status().isOk());
}
}
The repositories look like this:
public interface ARepository extends CrudRepository<A, Long>
{
Collection<A> findAll();
}
public interface BRepository extends CrudRepository<B, Long>
{
Collection<B> findAll();
}
A and B them self are JPA annotated classes. The whole application contains access to a database..
Furthermore I have a Service like this:
#Service
public class XService {
private static final Logger LOGGER = LoggerFactory.getLogger(XService.class);
#Autowired
private ARepository aRepository;
#Autowired
private BRepository bRepository;
...
}
The XService is not used via #Autowire or so (Just need to remove that):
So I try to run the AControllerTest I get the following error:
java.lang.IllegalStateException: Failed to load ApplicationContext at
org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
.. .. at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
Caused by:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'XService': Unsatisfied dependency
expressed through field 'BRepository'; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'BRepository' available: expected at least 1
bean which qualifies as autowire candidate. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
.. .. 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)
... 26 more Caused by:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'BRepository' 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.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1493)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
... 44 more
My assumption is that during the test more context is started than it should. The question is how can I prevent that? Which means only to start the context for the AControler and nothing more? I thought that based on the #WebMvcTest(AController.class) it should be limited already which looks like that it was not the case...
The referenced answer does not really answered my question but a in the context a hint gave me the solution. This means in consequence to add the following to my test:
so I have to add #OverrideAutoConfiguration(enabled=true):
#RunWith(SpringRunner.class)
#WebMvcTest(OrgtFarbenController.class)
#OverrideAutoConfiguration(enabled=true)
public class AControllerTest {
...
}
I'm working on a Spring MVC and MongoDB backed application.
My api is working fine,but i would like to create an integration test with Fongo in order to test saving a file and after getting this file by my services.
I have already tried, but when i added #Autowired in my Service class, it returned an UnsatisfiedDependencyException. My test fixture class is the following:
#ActiveProfiles({"test"})
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(
locations = {
"classpath*:config/servlet-config.xml",
"classpath*:config/SpringConfig.xml"})
#WebAppConfiguration
public class IntegrationTest {
#Autowired // returns UnsatisfiedDependencyException
private FileService fileService;
#Before
#Test
public void setUp() throws IOException {
Fongo fongo = new Fongo("dbTest");
DB db = fongo.getDB("myDb");
}
#Test
public void testInsertAndGetFile() throws IOException{
//create a file document in order to save
File file = new File();
file.setId("1");
file.setFileName("test1");
file.setVersionId("1");
//save the file
String id = fileService.storeFile(file);
//get the file
File fileDocument= fileService.getFileById("1");
//check if id is the file id which is expected
assertEquals(fileDocument.getId(), "1");
}
}
and i am receiving this log message:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.ots.openonefilesystem.integration.IntegrationTest': Unsatisfied dependency expressed through field 'fileService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean found for dependency [com.myproject.service.FileService]: 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 found for dependency [com.myproject.service.FileService]: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
I'm using xml configuration.
How can i solve my testing error? In my service class FileService i have put #Service, however it seems that Spring expected at least 1 bean which qualifies as autowire candidate.
Also if i remove the #Autowired, the log returns NullpointerException when saving of getting the file,as it was expected.
PS: I use springFramework 4.3.3.RELEASE, spring-data-mongodb 1.9.5.RELEASE
Thank you in advance!
I had to configure Mock Database (Fongo), in order to #Autowired FileService. This, I made it via #ContextConfiguration(classes = {MockDatasourceConfig.class})
So, the correct test fixture class is the following:
#ActiveProfiles({"test"})
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {MockDatasourceConfig.class})
#WebAppConfiguration
public class IntegrationTest{
#Autowired
private FileService fileService;
#Test
public void testInsertAndGetFile() throws IOException{
//create a file document in order to save
File file = new File();
file.setId("1");
file.setFileName("test1");
file.setVersionId("1");
//save the file and return his id
String id = fileService.storeFileGeneral(file);
//get the file
FileDocument fileDocument= fileService.getFileById(id);
//check that the file isn't null
assertNotNull(fileDocument);
//check if id is the file id which is expected
assertEquals(fileDocument.getId(), id);
assertEquals(fileDocument.getFileName(), "test1");
}
}
and the MockDatasourceConfig class is the following:
#Profile({"test"})
#Configuration
#PropertySource("classpath:mongo.properties")
#ComponentScan(basePackageClasses = {File.class})
#EnableMongoRepositories(basePackageClasses = RepositoryPackageMarker.class)
public class MockDatasourceConfig extends AbstractMongoConfiguration {
#Autowired
Environment env;
#Override
protected String getDatabaseName() {
return env.getProperty("mongo.dbname", "myDb");
}
#Override
public Mongo mongo() throws Exception {
return new Fongo(getDatabaseName()).getMongo();
}
#Bean
public GridFsTemplate gridFsTemplate() throws Exception {
return new GridFsTemplate( mongoDbFactory(),mappingMongoConverter());
}
}
P.S: With helpful advice of #M.Deinum