Search code examples
javaspringspring-bootjunitspring-boot-test

Spring boot test: Unable to instantiate inner configuration class


I want to run JUnit tests for my DAO layer without involving my main Spring configurations. As such, I declared an inner class annotated with @Configuration so that it would override the configurations of the main application class annotated with @SpringBootApplication.

This is the code:

@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);

    }

}

But I'm getting the error:

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.

Solution

  • Any nested configuration classes must be declared as static. So your code should be :

    @Configuration
    static class TestConfiguration{
    
        @Bean
        public InterviewInformationDao getInterviewInformationDao(){
            return new InterviewInformationDaoImpl();
        }
    }