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?
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With