Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have DBUnit @DatabaseSetup to happen before spring autowiring?

Consider the typical DBUnit Spring Test (see https://github.com/springtestdbunit/spring-test-dbunit) :

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"classpath:/META-INF/spring/applicationContext-database.xml",
"classpath:spring-*.xml"
})
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
    DirtiesContextTestExecutionListener.class,
    TransactionalTestExecutionListener.class,
    DbUnitTestExecutionListener.class })
@DatabaseSetup("/dbunit/data.xml")
public class UnitTest {

    @Autowired
    private UnitUnderTest uut;

    @Test
    public void shouldInitDB() {
         ...
    }
}

What I have verified is that, and has expected, Autowiring will happen before DatabaseSetup. This must happen because DBUnit depends on the application context to provide the configured data source.

The problem is that the UnitUnderTest bean has a @PostConstruct where it loads some data from the DB but, since the Autowiring happens before the DBunit setup, the data will not be available at this stage.

Any ideas on how to solve this issue in a clean way?

like image 575
Bruno Santos Avatar asked Nov 12 '22 17:11

Bruno Santos


1 Answers

You can you Spring's ResourceDatabasePopulator.

I think you can use something like this

@PostConstruct
public void myInMemryPopulator() {
final ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();

        try {

            Resource[] array = resourceResolver.getResources("classpath:/*.sql");       

            for (Resource resource : array) {

                databasePopulator.addScript(resource);
            }
            databasePopulator.populate(dataSource.getConnection());

        } catch (IOException | SQLException e) {
            LOGGER.error("Error in databasePopulator  {} ", e);
        }

    } 
like image 125
Niraj Sonawane Avatar answered Nov 15 '22 12:11

Niraj Sonawane