Spring Boot测试:无法实例化内部配置类

时间:2019-03-13 13:23:51

标签: 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 个答案:

答案 0 :(得分:2)

任何嵌套配置类都必须声明为静态。因此您的代码应为:

@Configuration
static class TestConfiguration{

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