I have very simple SpringBoot Junit but it keeps failing.
#RunWith(SpringRunner.class)
//#SpringBootTest
#WebMvcTest(TokenServiceImpl.class)
public class TokenTest {
#Test
public void getOauthToken()
{
System.out.println( " done test");
}
my TokenServiceImpl class has
public class TokenServiceImpl implements TokenService{
public String getToken() throws RuntimeException{
return " Token returned" ;
}
I get the below error : -Snippet
2019-11-27 19:12:45.884 WARN 15864 --- [ main]
o.s.w.c.s.GenericWebApplicationContext : Exception encountered
during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'runApplication': Unsatisfied dependency
expressed through field 'job'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'job' defined in class path resource
[com/mycompany/project1/batch/configurations/BatchBDREntityConfig.class]:
Unsatisfied dependency expressed through method 'job' parameter 4;
nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'batchDBWriter': Unsatisfied dependency
expressed through field 'BDREntityRepository'; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'com.mycompany.project1.batch.repositories.BDREntityRepository'
available: expected at least 1 bean which qualifies as autowire
candidate. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
Field BDREntityRepository in
com.mycompany.project1.batch.services.BatchDBWriter required a bean of
type 'com.mycompany.project1.batch.repositories.BDREntityRepository'
that could not be found.
Consider defining a bean of type
'com.mycompany.project1.batch.repositories.BDREntityRepository' in
your configuration.
Caused by:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'runApplication': Unsatisfied dependency
expressed through field 'job'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'job' defined in class path resource
[com/mycompany/project1/batch/configurations/BatchBDREntityConfig.class]:
Unsatisfied dependency expressed through method 'job' parameter 4;
nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'batchDBWriter': Unsatisfied dependency
expressed through field 'BDREntityRepository'; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'com.mycompany.project1.batch.repositories.BDREntityRepository'
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.UnsatisfiedDependencyException:
Error creating bean with name 'batchDBWriter': Unsatisfied dependency
expressed through field 'BDREntityRepository'; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'com.mycompany.project1.batch.repositories.BDREntityRepository'
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
'com.mycompany.project1.batch.repositories.BDREntityRepository'
available: expected at least 1 bean which qualifies as autowire
candidate. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
My main method has following
#SpringBootApplication
#ComponentScan(basePackages= {"com.mycompany.project1"})
public class RunApplication{
private static final Logger logger = Logger.getLogger(BatchController.class);
#Autowired
JobLauncher jobLauncher;
#Autowired
Job job;
/*
* jmxBean will get loaded when this managed bean is called from RMI, and it will fire batch execution
*/
public static void main(String[] args){
ApplicationContext app = SpringApplication.run(RunApplication.class, args);
logger.debug("Batch Application has been started...");
BatchController controller = app.getBean(BatchController.class);
//Start batch process when application starts or restart, its optional call and can be commented out
//as we have JMX to expose load method on demand
//BatchController batch = new BatchController();
controller.startBatchProessFromMain();
}
}
#Component
public class BatchDBWriter implements ItemWriter<BDREntity> {
private static final Logger logger = Logger.getLogger(BatchDBWriter.class);
#Autowired
private BDREntityRepository bDREntityRepository;
/*
* this method call the JPArepository's saveAll
* function and saves all the list of bdrEntitiesat a time.
*/
#Override
public void write(List<? extends BDREntity> bdrEntities) throws Exception {
bDREntityRepository.saveAll(bdrEntities);
}
}
How can i fix my Junit ?
You are using #WebMvcTest that is a test-slice annotation. It's specifically intended for testing the WebMvc-related components in your application and is a form of integration test.
You've said in the comments that you're not trying to integration test your application. In that case, you should not be using #SpringBootTest or any of the other #…Test annotations that are provided by Spring Boot.
Assuming that your goal is to unit test TokenServiceImpl, I'd expect your test class to look something like this:
public class TokenTest {
private final TokenServiceImpl tokenService = new TokenServiceImpl();
#Test
public void getOauthToken() {
String token = this.tokenService.getToken();
// Assertions to check the token go here
}
}
Related
**I am getting below error even though i have down the #autowired .please some one let me know why this issue happening its a ant build with spring config
utor.
2022-07-08 10:18:09,856 WARN org.springframework.context.support.
ClassPathXmlApplicationContext - Exception encountered during context initialization
cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'delegateProcessor':
Unsatisfied dependency expressed through field 'headerProcessor';
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean found for dependency
[org.springframework.batch.item.ItemProcessor<com.abc.proj.model.FileHeader,
com.abc.proj.model.FileHeader>]:
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=headerProcessor)}
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'delegateProcessor': Unsatisfied dependency expressed
through field 'headerProcessor';
nested exception is org.springframework.beans.factory.
NoSuchBeanDefinitionException: No qualifying bean found for dependency
[org.springframework.batch.item.ItemProcessor<com.abc.proj.model.FileHeader,
com.abc.proj.model.FileHeader>]: 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=headerProcessor)}
#Component
public class DelegateProcessor implements ItemProcessor<Object, Object>, InitializingBean {
#Autowired
#Qualifier("headerProcessor")
private ItemProcessor<FileHeader, FileHeader> headerProcessor;
#Autowired
#Qualifier("detailProcessor")
private ItemProcessor<FileDetail, FileDetail> detailProcessor;
#Autowired
#Qualifier("trailerProcessor")
private ItemProcessor<FileTrailer, FileTrailer> trailerProcessor;
#Component
public class HeaderProcessor implements ItemProcessor<Object, Object>{
#Autowired
private HeaderValidatorDao headerValidatorDao ;**
With a configuration class you could initialize your beans manually, specially if they need custom names.
#Configuration
public class MyCustomConfiguration {
#Bean(name ="headerProcessor")
public ItemProcessor<FileHeader, FileHeader> headerProcessorBean() {
ItemProcessor<FileHeader, FileHeader> myBean = new HeaderProcessor<>();
//Do whaterever you need to initilize your bean
return myBean;
}
#Bean(name ="detailProcessor")
public ItemProcessor<FileDetail, FileDetail> detailProcessorBean() {
ItemProcessor<FileDetail, FileDetail> myBean = new ItemProcessor<>();
//Do whaterever you need to initilize your bean
return myBean;
}
}
In this way these beans will be available for autowiring.
I wanted to move from JdbcTemplate to Spring Data JDBC. However I seem to have some misconfiguration but I cannot figure out where. The errors are "expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}" and "Parameter 0 of constructor ... required a bean ... that could not be found."
I put #Repository on the public repository interfaces extending PagingAndSortingRepository (as I did with the DAO classes extending from JdbcDaoSupport) without success. Then I added #EnableJdbcRepositories with and without package name to the database config class, also no success. I also tried the database config to inherit from AbstractJdbcConfiguration, still the same errors ...
Unfortunately I couldn't find a working example and I now gave up after some trial and error. I still would love to get this working, the version I used is spring-boot-starter-data-jdbc:2.4.0
Code fragments:
DatabaseConfiguration.java
#Configuration
#EnableJdbcRepositories("<basepackage>.repository.jdbc")
#EnableJdbcAuditing(auditorAwareRef = "springSecurityAuditorAware")
#EnableJpaRepositories("<basepackage>.repository")
#EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware")
#EnableTransactionManagement
#EnableElasticsearchRepositories("<basepackage>.repository.search")
public class DatabaseConfiguration extends AbstractJdbcConfiguration {
}
UserRepository.java
#Repository
public interface UserRepository extends PagingAndSortingRepository<User, String> {
}
QualityResource.java (REST Controller)
public QualityResource(UserRepository userRepository) {
this.userRepository = userRepository;
}
Error messages:
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'qualityResource' defined in file [.../backend/build/classes/java/main/.../web/rest/QualityResource.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type '....repository.jdbc.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Application failed to start: Description: Parameter 0 of constructor in <basepackage>.web.rest.QualityResource required a bean of type '<basepackage>.repository.jdbc.UserRepository' that could not be found.
I am trying to unit test my rest api controller. Controller code is as below
#RestController
#RequestMapping("/events")
public class EventController {
#Autowired
private EventService eventService;
#GetMapping
public Iterable<Event> getEvents(EventSearchFilter filter, #PageableDefault(page = 1, size = 5, sort = "location.city, asc") Pageable pageable) {
return eventService.findEventsOnCondition(filter, pageable);
}
...
}
Test class is
#RunWith(SpringRunner.class)
#WebMvcTest(EventController.class)
public class EventEndpointTest {
private MockMvc mockMvc;
#InjectMocks
private EventController eventController;
#Mock
private EventService eventService;
#InjectMocks
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(eventController).setCustomArgumentResolvers(pageableArgumentResolver).build();
}
#Test
public void getEvents() throws Exception{
Event event = new Event();
event.setName("TestName");
EventSearchFilter filter = new EventSearchFilter();
filter.setName("TestName");
List<Event> eventList = singletonList(event);
given(eventController.getEvents(any(EventSearchFilter.class), any(PageRequest.class))).willReturn(eventList);
mockMvc.perform(get("/events")
.contentType(APPLICATION_JSON))
.andExpect(status().isOk());
}
...
}
However, I got error complaining saying I have Error creating bean with name 'eventController':
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'EventService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}.
As I got above error, I tried use Autowired annotation for my EventService. It still doesn't work. any ideas? Thanks.
I found a solution. All I need to do is replacing #WebMvcTest(EventController.class) in my Test class to #SpringBootTest(classes = Application.class). Thanks guys.
Did you declare #Service annotation at EventService?
#Service
public class EventService {
...something code..
}
I guess Spring cannot find bean named EventService
I had a similar issue where the stack trace showed
java.lang.IllegalStateException: Failed to load ApplicationContext
...
...
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'Controller': Unsatisfied dependency expressed through field 'i18NService';
...
...
...
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type '...Service' available:
...
...
...
and ultimately the solution was that the services needed to be mocked with #MockBean since regular components (including services and repositories) will not be scanned.
Same answer with #DFeng. Encountered the below error:
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mysqlRedisCachingController': Unsatisfied dependency expressed through field 'mysqlRedisBusinessService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mysqlRedisBusinessService': Unsatisfied dependency expressed through field 'mysqlRedisService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mysqlRedisService': Unsatisfied dependency expressed through field 'mysqlRedisRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.caching.redismanager.repo.MysqlRedisRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.example.caching.redismanager.repo.MysqlRedisRepository' in your configuration.
This annotation did the trick.
#MockBean
Added the below in the Test Class:
#MockBean
private MysqlRedisRepository mysqlRedisRepository;
#Test
void contextLoads() {}
It works as expected. Hope this helps.
I am using spring retry (http://docs.spring.io/spring-retry/docs/1.1.2.RELEASE/apidocs/) in a maven project and I have the following unit test
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration
public class RetriableFileManagerTest {
#Autowired
#Qualifier("asset")
private AssetResource assetResource;
#Test
public void testRetry() throws URISyntaxException {
byte[] image = this.assetResource.fetchResource("name", "path");
verify(assetResource, times(3)).fetchResource("name", "path");
Assert.assertEquals("should be equal", "image", new String(image));
}
#Configuration
#EnableRetry
public static class SpringConfig {
#Bean(name = "asset")
public AssetResource assetResource() throws Exception {
AssetResource remoteService = mock(AssetResource.class);
when(remoteService.fetchResource(anyString(), anyString()))
.thenThrow(new RuntimeException("Remote Exception 1"))
.thenThrow(new RuntimeException("Remote Exception 2"))
.thenReturn("Completed".getBytes());
return remoteService;
}
}
}
However when I try to run the test it fails with
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private ctp.cms.actions.handlers.repository.resources.AssetResource ctp.cms.actions.handlers.filemanager.RetriableFileManagerTest.assetResource; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [ctp.cms.actions.handlers.repository.resources.AssetResource] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true), #org.springframework.beans.factory.annotation.Qualifier(value=asset)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 25 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [ctp.cms.actions.handlers.repository.resources.AssetResource] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true), #org.springframework.beans.factory.annotation.Qualifier(value=asset)}
Finally figured out the issue, I had to move the #Retryable annotation to the interface that AssetResource implements and autowire this interface type to the unit test.
Error message says
No qualifying bean of type
[ctp.cms.actions.handlers.repository.resources.AssetResource] found
for dependency
How is ctp.cms.actions.handlers.repository.resources.AssetResource declared?
Do you have #Component (#Service or similar annotation on it?) Is this package enabled for #ComponentScan ?
I am using spring #Transactional to manage MySQL transactional.
But the way I add #Transactional is wrong.
#Service
//#Transactional(readOnly = true)
public class UserInfoService extends BaseService
#Autowired
private UserInfoAccessor userInfoAccessor;
//#Transactional
public void insert()
Map<String, String> map = new HashMap<>();
map.put("userName", "test");
userInfoAccessor.insert(map);
The error message I receive is:
Unable to instantiate Action, com.luotuo.xiaobao.action.IndexAction, defined for 'index' in namespace '/'Error creating bean with name 'com.luotuo.xiaobao.action.IndexAction': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.luotuo.xiaobao.service.UserInfoService com.luotuo.xiaobao.action.IndexAction.userInfoService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.luotuo.xiaobao.service.UserInfoService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: #org.springframework.beans.factory.annotation.Autowired(required=true)
You can download my project source here.
What is the correct way to set this up?