Тест загрузки Spring: не удалось создать экземпляр класса внутренней конфигурации

#java #spring #spring-boot #junit #spring-boot-test

#java #spring #spring-boot #junit #spring-boot-test

Вопрос:

Я хочу запускать JUnit тесты для моего DAO уровня без участия моих основных конфигураций Spring. Таким образом, я объявил внутренний класс, аннотированный с помощью @Configuration , чтобы он переопределял конфигурации основного класса приложения, аннотированного с помощью @SpringBootApplication .

Это код:

 @RunWith(SpringRunner.class)
@JdbcTest
public class InterviewInformationControllerTest {

    @Configuration
    class TestConfiguration{

        @Bean
        public InterviewInformationDao getInterviewInformationDao(){
            return new InterviewInformationDaoImpl();
        }
    }

    @Autowired
    private InterviewInformationDao dao;

    @Test
    public void testCustomer() {
        List<Customer> customers = dao.getCustomers();
        assertNotNull(customers);
        assertTrue(customers.size() == 4);

    }

}
  

Но я получаю сообщение об ошибке:

 Parameter 0 of constructor in com.test.home.controller.InterviewInformationControllerTest$TestConfiguration required a bean of type 'com.test.home.controller.InterviewInformationControllerTest' that could not be found.
  

Ответ №1:

Все вложенные классы конфигурации должны быть объявлены как статические. Итак, ваш код должен быть :

 @Configuration
static class TestConfiguration{

    @Bean
    public InterviewInformationDao getInterviewInformationDao(){
        return new InterviewInformationDaoImpl();
    }
}