Unsatisfied dependency expressed through field - Springboot the Application, the component and the test class are all in the same package - spring-boot

My understanding is that the SpringBootApplication annotation includes
ComponentScan
https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-using-springbootapplication-annotation.html
The bean is discovered and printed in Application.main(), why does the unit test not find it?
This unit test fails with:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.pds.pdssr.etlfile.EtlFileServicesTest': Unsatisfied dependency expressed through field 'etlFileServices'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.pds.pdssr.etlfile.EtlFileServices' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
With the appropriate level of debug, i.e "org.springframework.context.annotation"="debug" I can see that the bean was discovered during component scanning.
Nevertheless, the unit test results in:
[ERROR] getAll(com.pds.pdssr.etlfile.EtlFileServicesTest) Time elapsed: 0.007 s <<< ERROR!
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.pds.pdssr.etlfile.EtlFileServicesTest': Unsatisfied dependency expressed through field 'etlFileServices'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.pds.pdssr.etlfile.EtlFileServices' 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.pds.pdssr.etlfile.EtlFileServices' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
The Application:
package com.pds.pdssr.bootstrap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
//#EnableJpaRepositories("com.pds.pdsssr.jpa")
#SpringBootApplication
// #EntityScan("com.pds.pdssr.models")
public class Application {
private static final Logger logger = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
ApplicationContext applicationContext = SpringApplication.run(Application.class, args);
for (String name : applicationContext.getBeanDefinitionNames()) {
logger.info("bean: " + name);
}
}
}
The Component:
package com.pds.pdssr.bootstrap;
import java.util.List;
import javax.persistence.EntityManagerFactory;
import javax.transaction.Transactional;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.pds.pdssr.models.EtlFile;
#Repository
public class EtlFileServices {
#Autowired
private static EntityManagerFactory entityManagerFactory;
public SessionFactory getSessionFactory() {
SessionFactory sessionFactory = null;
if (entityManagerFactory == null) {
throw new IllegalStateException("entityManagerFactory is null");
}
sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
if (sessionFactory == null) {
throw new NullPointerException("factory is not a hibernate factory");
}
return sessionFactory;
}
#SuppressWarnings("unchecked")
public List<EtlFile> getAll() {
return getAll("etlFile",getSessionFactory().getCurrentSession());
}
#SuppressWarnings("rawtypes")
protected List getAll(String tableName, Session session) {
String queryText = "from " + tableName;
return getList(tableName, queryText, session);
}
#SuppressWarnings("rawtypes")
protected List getList(String tableName, String queryText, Session session) {
long start = System.nanoTime();
Query query = session.createQuery(queryText);
List result = query.list();
long end = System.nanoTime();
long millis = (end - start) / 1000000;
//logger.debug("table: " + tableName + " millis " + millis + " rows: " + result.size());
return result;
}
}
The test class:
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit4.SpringRunner;
import com.pds.pdssr.bootstrap.EtlFileServices;
import com.pds.pdssr.models.EtlFile;
#RunWith(SpringRunner.class)
public class EtlFileServicesTest {
#Autowired
private EtlFileServices etlFileServices;
#Test
public void getAll() {
List<EtlFile> etlFiles = etlFileServices.getAll();
assertNotNull(etlFiles);
}
}

Original answer:
You need to have
#RunWith(SpringRunner.class)
#SpringBootTest(classes = YourMainClass.class)
in your test class(es).
Further answer based on comment
If you really want to have SessionFactory in your project, you need to tell spring framework to have SessionContext explicitly. It can be done by add
spring.jpa.properties.hibernate.current_session_context_class = org.springframework.orm.hibernate5.SpringSessionContext
to your configuration file. Here's a working example for your problem.
HTH

Related

"UnsatisfiedDependencyException: Error creating bean with name ..." when running unit test on controller

So I have a controller class:
package microservices.book.multiplication.controller;
import microservices.book.multiplication.domain.MultiplicationResultAttempt;
import microservices.book.multiplication.repository.MultiplicationResultAttemptRepository;
import microservices.book.multiplication.service.MultiplicationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
#RestController("MultiplicationResultAttemptController")
#RequestMapping("/results")
final class MultiplicationResultAttemptController {
private static final Logger logger = LoggerFactory.getLogger(MultiplicationResultAttemptController.class);
private final MultiplicationService multiplicationService;
private final MultiplicationResultAttemptRepository attemptRepository;
#Autowired
public MultiplicationResultAttemptController(MultiplicationService multiplicationService,
MultiplicationResultAttemptRepository attemptRepository) {
this.multiplicationService = multiplicationService;
this.attemptRepository = attemptRepository;
}
}
And the relative test class is:
package microservices.book.multiplication.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import microservices.book.multiplication.domain.Multiplication;
import microservices.book.multiplication.domain.MultiplicationResultAttempt;
import microservices.book.multiplication.domain.User;
import microservices.book.multiplication.service.MultiplicationService;
import org.assertj.core.util.Lists;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.json.JacksonTester;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import java.util.List;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.assertj.core.api.Assertions.assertThat;
#RunWith(SpringRunner.class)
#WebMvcTest(controllers = MultiplicationResultAttemptController.class)
#TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class MultiplicationResultAttemptControllerTest {
#MockBean
MultiplicationService multiplicationService;
#Autowired
private MockMvc mvc;
private JacksonTester<MultiplicationResultAttempt> jsonResult;
private JacksonTester<MultiplicationResultAttempt> jsonResponse;
private JacksonTester<List<MultiplicationResultAttempt>> jsonResultAttemptList;
#BeforeAll
void initAll(){
JacksonTester.initFields(this, new ObjectMapper());
}
#Test
public void postResultReturnCorrect() throws Exception{
genericParameterizedTest(true);
}
#Test
public void postResultReturnNotCorrect() throws Exception{
genericParameterizedTest(true);
}
void genericParameterizedTest(final Boolean correct) throws Exception{
given(multiplicationService.checkAttempt(any(MultiplicationResultAttempt.class))).willReturn(correct);
User user = new User("Smith");
Multiplication multiplication = new Multiplication(50,70);
MultiplicationResultAttempt attempt = new MultiplicationResultAttempt(user, multiplication, 3500, false);
// when
MockHttpServletResponse response = mvc.perform(
post("/results").contentType(MediaType.APPLICATION_JSON).
content(jsonResult.write(attempt).getJson())).
andReturn().getResponse();
// then
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(response.getContentAsString()).isEqualTo(
jsonResponse.write(new MultiplicationResultAttempt(attempt.getUser(),
attempt.getMultiplication(),
attempt.getResultAttempt(),
correct)).getJson());
}
#Test
public void getUserStats() throws Exception {
// given
User user = new User("john_doe");
Multiplication multiplication = new Multiplication(50, 70);
MultiplicationResultAttempt attempt = new MultiplicationResultAttempt(user, multiplication, 3500,true);
List<MultiplicationResultAttempt> recentAttempts = Lists.newArrayList(attempt, attempt);
given(multiplicationService.getStatsForUsers("john_doe")).willReturn(recentAttempts);
// when
MockHttpServletResponse response = mvc.perform(
get("/results").param("alias", "john_doe")).andReturn().getResponse();
// then
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(response.getContentAsString()).isEqualTo(jsonResultAttemptList.write(recentAttempts).getJson());
}
}
When I run this test class I get the error:
-------------------------------------------------------------------------------
Test set: microservices.book.multiplication.controller.MultiplicationResultAttemptControllerTest
-------------------------------------------------------------------------------
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 2.715 s <<< FAILURE! - in microservices.book.multiplication.controller.MultiplicationResultAttemptControllerTest
microservices.book.multiplication.controller.MultiplicationResultAttemptControllerTest Time elapsed: 2.715 s <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'MultiplicationResultAttemptController' defined in file [C:\Users\pinguino\Desktop\Programming\social-multiplication\social-multiplication\target\classes\microservices\book\multiplication\controller\MultiplicationResultAttemptController.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'microservices.book.multiplication.repository.MultiplicationResultAttemptRepository' 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 'microservices.book.multiplication.repository.MultiplicationResultAttemptRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Now, I can build the application with success.
The only line where the controller is mentioned in the test class is as parameter to the #WebMvcTest annotation. The repository which can't be found is this:
package microservices.book.multiplication.repository;
import microservices.book.multiplication.domain.MultiplicationResultAttempt;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface MultiplicationResultAttemptRepository extends CrudRepository<MultiplicationResultAttempt, Long> {
List<MultiplicationResultAttempt> findTop5ByUserAliasOrderByIdDesc(String userAlias);
}
I've also tried to add #Repository on the class but I get the same result.

Spring Boot issue in join table query in my repository code

Getting unsatisfied dependency error while using #Query in Spring Boot
In my repository I have added query to join tables but getting error at runtime
ERROR:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'empcontroller': Unsatisfied dependency expressed through field 'emprepo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeRepository' defined in com.emp.employeeMangement.api.Repository.EmployeeRepository defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.util.List com.emp.employeeMangement.api.Repository.EmployeeRepository.getJoinInformation(); Reason: Validation failed for query for method public abstract java.util.List com.emp.employeeMangement.api.Repository.EmployeeRepository.getJoinInformation()!; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List com.emp.employeeMangement.api.Repository.EmployeeRepository.getJoinInformation()!
My code:
package com.emp.employeeMangement.api.Repository;
import com.emp.employeeMangement.api.DTO.ResponseDTO;
import com.emp.employeeMangement.api.Model.Employee;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public interface EmployeeRepository extends JpaRepository<Employee,Long> {
#Query(value = "SELECT new com.emp.employeeMangement.api.DTO.ResponseDTO(e.empName,e.gender,e.email,e.empCode,a.noOfPresent,a.noOfAbsent) from Employee e JOIN e.Attendence a")
public List<ResponseDTO> getJoinInformation();
}
My controller code:
package com.emp.employeeMangement.api.Controller;
import com.emp.employeeMangement.api.DTO.RequestDTO;
import com.emp.employeeMangement.api.DTO.ResponseDTO;
import com.emp.employeeMangement.api.Exception.ResourceNotFoundException;
import com.emp.employeeMangement.api.Model.Employee;
import com.emp.employeeMangement.api.Repository.AttendenceRepository;
import com.emp.employeeMangement.api.Repository.EmployeeRepository;
import com.emp.employeeMangement.api.Repository.SalaryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
public class Empcontroller {
#Autowired
private EmployeeRepository emprepo;
#Autowired
private AttendenceRepository attrepo;
#Autowired
private SalaryRepository salRepo;
#PostMapping("/saveEmployee")
public Employee saveEmployee(#RequestBody RequestDTO dto){
return emprepo.save(dto.getEmployee());
}
#GetMapping("/findAllEmp")
public List<Employee> findAllEmp(){
return emprepo.findAll();
}
#GetMapping("/getInfo")
public List<ResponseDTO> getJoinInformation(){
return emprepo.getJoinInformation();
}
My response to:
package com.emp.employeeMangement.api.DTO;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
#Data
#AllArgsConstructor
#NoArgsConstructor
#ToString
public class ResponseDTO {
private String empName;
private String email;
private String gender;
private int empCode;
private int noOfPresent;
private int noOfAbsent;
private int salAmount;
}
Spring Data tells you that the query is invalid. After a quick look it seems you are missing the field salAmount in the constructor.

Error in running sample Spring annotation based program without any xml

Hi I am trying to run a simple spring annotation based program without using any xml based configuration. I'm getting the error "Unsatisfied dependency expressed through field".
I learnt that using #ComponentScan spring scans the package mentioned and look for beans annotated.
Putting the code herein. My project is a maven project with hierarchy like MyProject/src/java/SpringAnnotnDemo/autowireAnnotationBased
There are three classed
Department.java
Employee.java
MainClass.java --> The main class
Department.java
package SpringAnnotnDemo.autowireAnnotationBased;
import org.springframework.stereotype.Component;
#Component
public class Department {
private String department;
public String getDeptName() {
return department;
}
public void setDeptName(String deptName) {
this.department = deptName;
}
}
Employee.java
package SpringAnnotnDemo.autowireAnnotationBased;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
#Component
public class Employee {
private int eid;
private String ename;
#Autowired
private Department department;
public int getEid() {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public void showEployeeDetails() {
System.out.println("Employee Id : " + eid);
System.out.println("Employee Name : " + ename);
department.setDeptName("Mechanical Engineering");
System.out.println("Department : " + department.getDeptName());
}
}
MainClass.java
package SpringAnnotnDemo.autowireAnnotationBased;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
#ComponentScan("SpringAnnotnDemo.autowireAnnotationBased")
public class MainClass {
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(Employee.class);
Employee emp = ctx.getBean(Employee.class);
emp.setEid(374);
emp.setEname("S.C.B");
emp.showEployeeDetails();
}
}
On running this simple program I am getting an error as below.
`Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'employee': Unsatisfied dependency expressed through field 'department'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'SpringAnnotnDemo.autowireAnnotationBased.Department' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}`
Can anyone please help me figure out what am I missing. I want the most simplest form of using annotation based spring without using any xml based configuration.
Change your this line
ApplicationContext ctx = new AnnotationConfigApplicationContext(Employee.class);
to this line
ApplicationContext ctx = new AnnotationConfigApplicationContext(MainClass.class);

No qualifying bean of type 'org.springframework.test.web.servlet.MockMvc

Spring boot 2
build.gradle:
dependencies {
implementation 'com.google.code.gson:gson:2.7'
implementation 'com.h2database:h2'
implementation 'javax.servlet:jstl:1.2'
implementation 'org.springframework.boot:spring-boot-devtools'
implementation 'org.springframework.boot:spring-boot-starter'
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.apache.tomcat.embed:tomcat-embed-jasper'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
testImplementation 'org.junit.jupiter:junit-jupiter:5.5.2'
}
test {
useJUnitPlatform()
}
User model:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
#Entity
public class User {
#Id
#GeneratedValue
private long id;
#NotNull
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "\nUser{" +
"id = " + id +
", name = '" + name + '\'' +
'}';
}
}
in my controller:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
#RestController
public class UserController {
private UserRepository userRepository;
// If class has only one constructore then #Autowired wiil execute automatically
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
User user = new User();
user.setName("Peter");
userRepository.save(user);
}
#GetMapping("/users")
public List<User> getAllUsers() {
List<User> usersList = new ArrayList<>();
userRepository.findAll().forEach(usersList::add);
return usersList;
}
}
My repo:
import org.springframework.data.repository.CrudRepository;
public interface UserRepository extends CrudRepository<User, Integer> {
}
and here my test:
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import java.util.ArrayList;
import java.util.List;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
#SpringBootTest
public class UserControllerTest {
#Autowired
private MockMvc mockMvc;
#MockBean
private UserRepository userVehicleService;
#Test
public void testExample() throws Exception {
List<User> userList = new ArrayList<>();
User user = new User();
user.setName("Peter");
userList.add(user);
given(this.userVehicleService.findAll()).willReturn(userList);
this.mockMvc.perform(MockMvcRequestBuilders.get("/users").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string("[{\"id\":\"1\",\"name\":\"Peter\"}]"));
}
}
Error creating bean with name 'com.myproject.UserControllerTest': Unsatisfied dependency expressed through field 'mockMvc'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.test.web.servlet.MockMvc' 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.UnsatisfiedDependencyException: Error creating bean with name 'com.myproject.UserControllerTest': Unsatisfied dependency expressed through field 'mockMvc'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.test.web.servlet.MockMvc' 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)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:116)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1422)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:393)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:119)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:43)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:244)
at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:98)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$5(ClassBasedTestDescriptor.java:337)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.executeAndMaskThrowable(ClassBasedTestDescriptor.java:342)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$6(ClassBasedTestDescriptor.java:337)
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:177)
at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1654)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.test.web.servlet.MockMvc' 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:1695)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1253)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640)
... 92 more
com.myproject.UserControllerTest > testExample() FAILED
org.springframework.beans.factory.UnsatisfiedDependencyException
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException
1 test completed, 1 failed
But when start test I get error:
Add #AutoConfigureMockMvc to your test class.

Spring Boot java.lang.IllegalArgumentException: Not a managed type

I'm trying to run a very simple Spring Boot application, but I get the following error messages:
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'todoController': Unsatisfied dependency expressed through field 'todoDAO'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'todoDAO': Unsatisfied dependency expressed through field 'todoRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'todoRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.ecominer.model.Todo
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'todoDAO': Unsatisfied dependency expressed through field 'todoRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'todoRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.ecominer.model.Todo
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'todoRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.ecominer.model.Todo
Caused by: java.lang.IllegalArgumentException: Not a managed type: class com.ecominer.model.Todo
Here is my main application class code:
package com.ecominer.network;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
#EnableJpaRepositories("com.ecominer.repository")
#EnableJpaAuditing
#ComponentScan({"com.ecominer.controller", "com.ecominer.dao", "com.ecominer.model"})
public class NetworkApplication {
public static void main(String[] args) {
SpringApplication.run(NetworkApplication.class, args);
}
}
and here is the Todo class:
package com.ecominer.model;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
#Entity
#Table(name="todos")
#EntityListeners(AuditingEntityListener.class)
public class Todo {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
protected Todo() {}
private String label;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
}
I tried to add the corresponding package name to my #ComponentScan annotation and I tried adding the #Component annotation to my Todo class, none of which worked.
Try to configure #EntityScan to the main class NetworkApplication
#EntityScan(basePackages = "com.ecominer.model")
public class NetworkApplication {
...
}

Resources