Spring 启动测试:无法实例化内部配置 class

Spring boot test: Unable to instantiate inner configuration class

我想 运行 JUnit 测试我的 DAO 层而不涉及我的主要 Spring 配置。因此,我声明了一个用 @Configuration 注释的内部 class,这样它将覆盖用 @SpringBootApplication.

注释的主应用程序 class 的配置。

这是代码:

@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.

任何嵌套配置 类 必须声明为静态 。所以你的代码应该是:

@Configuration
static class TestConfiguration{

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