I am trying to integrate PowerMockito with my spring boot unit test cases suite.
I am using consul to fetch my app configuration from the cloud.I am getting following exception while running junit testcases :
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.cloud.consul.config.ConsulConfigBootstrapConfiguration$ConsulPropertySourceConfiguration': Unsatisfied dependency expressed through field 'consul': Error creating bean with name 'consulClient' defined in org.springframework.cloud.consul.ConsulAutoConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.ecwid.consul.v1.ConsulClient]: Factory method 'consulClient' threw exception; nested exception is java.lang.NoClassDefFoundError: Could not initialize class com.ecwid.consul.v1.ConsulRawClient; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'consulClient' defined in org.springframework.cloud.consul.ConsulAutoConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.ecwid.consul.v1.ConsulClient]: Factory method 'consulClient' threw exception; nested exception is java.lang.NoClassDefFoundError: Could not initialize class com.ecwid.consul.v1.ConsulRawClient
Following is my code:
#SpringBootApplication
#EnableRetry
#EnableDiscoveryClient
#EnableScheduling
#ConfigurationProperties(prefix = "scheduler")
class TestApplication{
}
#ActiveProfiles("abc")
#RunWith(PowerMockRunner.class)
#PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
#PrepareForTest(KafkaClientUtil.class)
#SpringApplicationConfiguration(classes=TestApplication.class)
#FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ProcessorTest {
#Autowired
private TestClient Client;
#Test
public void test1() throws JsonProcessingException {
}
}
Related
Hi I have a spring boot project. The main class package is like this :
com.som.demo
I have used an external jar as a maven dependency in my project. In that jar there is a service class annotated with #Service as below :
#Service
public class SomeServiceImpl implements SomeService {
#Autowired
private TreeCacheWrapper ffCoreCache;
#Autowired(required = false)
private ZookeeperProperties zookeeperProperties;
public SomeServiceImpl(TreeCacheWrapper ffCoreCache, ZookeeperProperties zookeeperProperties) {
this.ffCoreCache = ffCoreCache;
this.zookeeperProperties = zookeeperProperties;
}
}
And the main package where this SomeServiceImpl class is as below :
com.som.test
Now in my project when I am autowiring the class I get the bean creation error while running the spring boot app. This is how I am doing :
#Autowired
private SomeService someService;
Error :
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'someServiceImpl'
Unsatisfied dependency expressed through field 'ffCoreCache';
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'ffCoreCache' defined in class path resource [com/som/test/config/ZooKeeperConfig.class]:
Bean instantiation via factory method failed;
nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [com.som.test.cache.TreeCacheWrapper]:
Factory method 'ffCoreCache' threw exception;
nested exception is java.lang.NoClassDefFoundError: org/apache/curator/retry/ExponentialBackoffRetry
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'ffCoreCache' defined in class path resource [com/som/test/config/ZooKeeperConfig.class]:
Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [com.som.test.cache.TreeCacheWrapper]:
Factory method 'ffCoreCache' threw exception; nested exception is java.lang.NoClassDefFoundError: org/apache/curator/retry/ExponentialBackoffRetry
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.som.test.cache.TreeCacheWrapper]:
Factory method 'ffCoreCache' threw exception; nested exception is java.lang.NoClassDefFoundError: org/apache/curator/retry/ExponentialBackoffRetry
Caused by: java.lang.NoClassDefFoundError: org/apache/curator/retry/ExponentialBackoffRetry
Caused by: java.lang.ClassNotFoundException: org.apache.curator.retry.ExponentialBackoffRetry
When spring boot application starts, it scans for beans in the same package as your main class, and all packages beneath it.
Since your main class resides in the package com.som.demo spring boot will find any beans in this package, or in packages like com.som.demo.sample1, com.som.demo.a.b.c etc
However it won't scan com.som.test package because its a "peer" to the main package.
In general you can configure spring boot to scan the packages of your choice with the help of #ComponentScan annotation that accepts a list of base packages to scan. You can put this annotation right on your main class (next to #SpringBootApplication).
However this is kind of against the conventions of spring boot.
Read this tutorial for more technical details and examples.
Annotate Service interface with #Service, not the Implementation class and try to annotate ServiceImplementation class with #Component.
Spring boot by default scan to beans in your main package. you can configure it using
#SpringBootApplication(scanBasePackages={"com.som.demo" , "com.som.test"})
I have a test class that make me crazy with this error :
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name .imprimirRelatorio: Unsatisfied
dependency expressed through field repository; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type v1.teste.Service available: expected at least
1 bean which qualifies as autowire candidate. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
After search in the web by a resolution, I couldn't run the test. The test class was like that:
#RunWith(SpringJUnit4ClassRunner.class)
public class imprimirRelatorio {
#Autowired
PautaService pautaRepository;
#Test
public void imprimirCabecalho(){
PautaReportBuilder pautaReportBuilder = new PautaReportBuilder();
//Reuniao reuniao = reuniaoService.findOne(UUID.fromString("4c7d3fc8-f78d-4ed3-a1ad-83c5da822ea7"));
try {
pautaReportBuilder.cabecalhoRelatorios(reuniao);
} catch (Exception e)
{
e.printStackTrace();
}
}
}
/*
Update
*/
So I forgot to say that I already tried the annotation #service in the pautaService interface. And the same on the test class I've tried to use the #SpringBootTest annotation. So the error messages was different.
The App.class
#SpringBootApplication
#ComponentScan({"br.com.empresa123.sistema123.*"})
public class App { public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
The interface PautaService:
#Service
public interface PautaService {
Page<Pauta> findAll(Pageable page);
Pauta findOne(UUID uuid);
Pauta save(Pauta pauta);
}
This is the first approach of my test , the nested exception were :
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'subjectController': Unsatisfied
dependency expressed through field 'subjectService'; nested exception
is org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'subjectService': Unsatisfied dependency
expressed through field 'domainSvc'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'dominio': Unsatisfied dependency
expressed through field 'domainRepo'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'domainReposImpl': Unsatisfied
dependency expressed through field 'sqlGenericPager'; nested exception
is org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'java.lang.String' available: expected at
least 1 bean which qualifies as autowire candidate. Dependency
annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true),
#org.springframework.beans.factory.annotation.Qualifier(value=sql-Generic-Pager)}
For integration test, add #SpringBootTest over your class.
In case where your file is not in the same packaging of your app, #ComponentScan() your app packaging.
I think you have forgot to annotate the service with the #Service annotation. If so, please tag the Service CLASS with #Service.
I solve this problem when I search by a annotation lost in my code that I never used it :
public abstract class BaseCustomRepository {
// the class code
#Autowired
#Qualifier("sql-Generic-Pager")
protected String sqlGenericPager;
}
I never used a Custom repository implementation so I will rethink what I will do with this class. Thanks a lot of the coders that lost their time to help me and the stack over flow to share my concerns.
I was laughing about this question, all the trouble was caused by me, like you do a git blame command in a class and see your user that made the wrong code.
I'm unable to solve this. I have a spring boot application.
Main class annotated with
#SpringBootApplication.
Test class annotated with:
#RunWith(SpringRunner.class)
#SpringBootTest
Everything is fine until i add a filter-configurer class in the application:
#Configuration
public class YadaYadaFilterConfigurer
{
#Bean
public FilterRegistrationBean<YadaYadaFilter> createYadaYadaFilter()
{...}
...
}
Boom!
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.web.servlet.FilterRegistrationBean]:
...
nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Failed to read candidate component class: URL [jar:file:...org.springframework.boot/spring-boot-test-autoconfigure/2.0.6.RELEASE/b0eb15474e795850dfa59b01ee6a83d7a39e3645/spring-boot-test-autoconfigure-2.0.6.RELEASE.jar!/org/springframework/boot/test/autoconfigure/jdbc/JdbcTest.class]; nested exception is java.lang.NoClassDefFoundError: org/springframework/dao/DataAccessException
My dependencies:
dependencies {
implementation('org.springframework.boot:spring-boot-starter-web')
testImplementation('org.springframework.boot:spring-boot-starter-test')
}
Some clearification.
Stripped so that I have only this test-class:
#RunWith(SpringRunner.class)
#SpringBootTest
public class JsonvalidationApplicationTests {
#Test
public void contextLoads() {
}
}
If comment out the #SpringBootTest then everything works. Seems like this annotation introduces a need for more dependencies?
Some more stacktrace:
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.web.servlet.FilterRegistrationBean]: Factory method 'createyadayadaFilter' threw exception; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Failed to read candidate component class: URL [jar:file:/C:/Users/66122872/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot-test-autoconfigure/2.0.6.RELEASE/b0eb15474e795850dfa59b01ee6a83d7a39e3645/spring-boot-test-autoconfigure-2.0.6.RELEASE.jar!/org/springframework/boot/test/autoconfigure/jdbc/JdbcTest.class]; nested exception is java.lang.NoClassDefFoundError: org/springframework/dao/DataAccessException
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:583)
... 67 more
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to read candidate component class: URL [jar:file:/C:/Users/66122872/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot-test-autoconfigure/2.0.6.RELEASE/b0eb15474e795850dfa59b01ee6a83d7a39e3645/spring-boot-test-autoconfigure-2.0.6.RELEASE.jar!/org/springframework/boot/test/autoconfigure/jdbc/JdbcTest.class]; nested exception is java.lang.NoClassDefFoundError: org/springframework/dao/DataAccessException
Sorry, after some more investigation i found that the problem is in my FilterRegistrationBean.
the exeption is thrown here.
ClassPathScanningCandidateComponentProvider provider = createComponentScanner();
provider.findCandidateComponents("").stream()...
I will answer this thread and create a new.
I'm just learning Spring and I've been struggling for the past couple of days on how to configure the Spring JdbcTemplate to use my PostgreSQL database. I don't know how to do this. I keep reading the documentation, (such as http://docs.spring.io/spring/docs/current/spring-framework-reference/html/jdbc.html) but it seems like I'm going around in circles.
From the errors thrown it seems that it can't instantiate the RelationalDatabase Class that I wrote as a bean. I'm not sure what it would take to instantiate the class properly.
How do I move from something like the guides (Like https://spring.io/guides/gs/relational-data-access/) which totally work to a more complex solution?
Relational Database Class
#Repository
public class RelationalDatabase
{
private JdbcTemplate jdbcTemplate;
public RelationalDatabase(){}
public RelationalDatabase(JdbcTemplate jdbcTemplate)
{
this.jdbcTemplate = jdbcTemplate;
}
#Autowired
public void setDataSource(javax.sql.DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
}
\src\main\resources\application-dev.properties
spring.datasource.url=jdbc:postgresql://192.168.56.102:5432/scibase
spring.datasource.type=org.postgresql.ds.PGPoolingDataSource
spring.datasource.username=lemon
spring.datasource.password=XXXXXX
spring.datasource.platform=postgres
spring.datasource.max-active=100
spring.datasource.name=lime
spring.database.driverClassName=org.postgresql.Drive
Stack Trace (Summary)
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'relationalDatabase': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire method: public void
com.scientifi.papers.db.relational.RelationalDatabase.setDataSource(javax.sql.DataSource);
nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'dataSource' defined in class path resource
[org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]:
Bean instantiation via factory method failed;
nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw
exception; nested exception is
org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException:
Cannot determine embedded database driver class for database type
NONE. If you want an embedded database please put a supported one on
the classpath. If you have database settings to be loaded from a
particular profile you may need to active it (the profiles "dev "
are currently active).
Thanks!
Did you forget the "r" in Driver? (Cannot determine embedded database driver class for database type NONE)
spring.database.driverClassName=org.postgresql.Driver
instead of
spring.database.driverClassName=org.postgresql.Drive
I Got the same Exception when i was testing my Spring Boot Application from Junit.
I resolved it using the #SpringApplicationConfiguration(classes = Application.class) above the Junit Test class. The Spring Boot application was not getting initialized properly
I'm getting this exception:
[WARN] org.springframework.web.context.support.GenericWebApplicationContext - Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'accountResource': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private io.ilopezluna.japanathome.service.UserService io.ilopezluna.japanathome.web.rest.AccountResource.userService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.security.crypto.password.PasswordEncoder io.ilopezluna.japanathome.service.UserService.passwordEncoder; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfiguration': Injection of autowired dependencies failed; nested exception is java.lang.IllegalStateException: Cannot apply org.springframework.security.config.annotation.authentication.configurers.userdetails.DaoAuthenticationConfigurer#54aa5730 to already built object
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:293) ~[spring-beans-4.0.7.RELEASE.jar:4.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1186) ~[spring-beans-4.0.7.RELEASE.jar:4.0.7.RELEASE]
You can see more on https://travis-ci.org/ilopezluna/japan-at-home/builds/37866955
This exception is thrown during my execution of tests. But I can't reproduce it on my localhost, I always get a build success :S
It took me two days, but I believe I've finally solved this. In my SecurityConfiguration class I had the following method:
#Configuration
#EnableWebMvcSecurity
#EnableGlobalMethodSecurity(jsr250Enabled=true, prePostEnabled=true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(authenticationService);
}
}
I replaced the configureGlobal method with a configure method:
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(authenticationService);
}
And now everything works fine.
According to this answer the difference is that the using configureGlobal will allow the AuthenticationManager by global method security or another HttpSecurity (WebSecurityConfigurerAdapter).
As you can see above, I am enabling both Web Mvc Security and global method security. According to my unit tests, both continue to work with this change, but there is some debate here at my office on whether this change is correct (ie, if it is configuring global method security correctly), or if there is another problem with this solution.
We believe the root cause of the problem is some type of Spring bug, possibly a race condition. As unlikely as that seems, the problem only manifested itself when we added a empty class to the project, it didn't matter what the class's package or name was.