Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't autowire Service class in Spring Boot Test

I created Dao Repository that uses jdbc for working with DB.

I autowired this repository in my Service class.

Then I try to autowire my service class in my test class.

@SpringBootTest
public class ServiceTest {
   @MockBean
   private Dao dao;

   @Autowired
   private Service service;

   @Test
   void whenSomething_thanSomething() {
      when(Dao.getStatus(anyString())).thenReturn("green");
      assertEquals(0, service.getStatus(""));
   }

   //other tests...

}

@Service
public class Service {
   private DaoImpl daoImpl;

   @Autowired
   public Service(DaoImpl daoImpl) {
      this.daoImpl = daoImpl;
   }

   //...

}

@Repository
public class DaoImpl omplements Dao {
   private NamedParameterJdbcOperations jdbc;
   
   @Autowired
   public DaoImpl(NamedParametedJdbcOperations jdbc) {
      this.jdbc = jdbc;
   }

   //...

}

When I start test I get the next error:

Parameter 0 of constructor in Service required a bean of type DaoImpl that could not be found.

How can I resolve my problem?

like image 781
Alexander Lopatin Avatar asked Sep 15 '25 21:09

Alexander Lopatin


1 Answers

Since you inject DaoImpl in your service-class you were probably intending to mock DaoImpl instead of Dao:

@SpringBootTest
public class ServiceTest {
   @MockBean
   private DaoImpl daoImpl;
   ...
}
like image 87
eol Avatar answered Sep 17 '25 13:09

eol