Am trying to write JUNIT test cases with H2 DB for my micorservices. I have some .sql files for initial set up of the DB, like creating the schema, tables etc. One issue am seeing here is that the .sql files are getting called multiple times, once per JUNIT test file. Is there any way to handle this scenario? My DB Set up file looks like this -
@Configuration
@ComponentScan(basePackages={"com.sample.repository"})
public class SampleDBConfig {
JdbcTemplate jdbcTemplate = null;
DataSource dataSource = null;
@Bean
public JdbcTemplate jdbcTemplate()
{
if(jdbcTemplate == null){
LOGGER.info("JdbcTemplate is null, so calling to create ");
jdbcTemplate = new JdbcTemplate(getDataSource());
}else{
LOGGER.info("JdbcTemplate is already set");
}
return jdbcTemplate;
}
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean
DataSource getDataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
if(dataSource == null){
dataSource = builder
.setType(EmbeddedDatabaseType.H2)
.addScript("classpath:folder/initial-setup.sql")
.build();
}
return dataSource;
}
}
One of my JUNIT test class looks like this -
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SampleDBConfig.class)
public class XyxImplTest{
@Autowired
ClassInTestImpl classInTestImpl ;
@Test
public void testMethod(){
.......
}
}
And one of the classes am testing are like this -
@Component
@Transactional(rollbackFor = Exception.class)
public class ClassInTestImpl implements ClassInTest {
@Autowired
private JdbcTemplate jdbcTemplate;
.....
I had the same problem. The quick fix I did is, I din configure the datasource bean. Added the relevant spring properties in the properties file which creates the datasource.
Also I used @Sql("classpath:data1.sql") on the first test, so the script ran only once for that testsuite. It worked for me.