samedi 28 février 2015

Spring4 JUnit tests : Load SQL to a H2 db

I'm trying to write tests for a Spring Boot (Spring 4) Application.


My Junit test class is configured like this to allow autowired.



@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringApp.class)
public class MyServiceTest {
...


My src/main/resources/application.properties is like this



spring.jpa.database=POSTGRESQL
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=update

spring.datasource.driverClassName=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost/mydb
spring.datasource.username=BNF0016779
spring.datasource.password=


In test context, src/test/resources/application.properties is just empty.


In can query the db as usual, creating objects...


But I'd like to create a data init sql.


To begin with a strange behavior, It seems that Spring loads any "schema.sql" in classpath. Something like the following is not required ?



//This is not required to execute schema.sql
@Configuration
public class DatabaseTestConfig {
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("classpath:schema.sql")
.build();
}
}


Then, I can't create any Table from this SQL. Always receive org.h2.jdbc.JdbcSQLException: Table "MY_TABLE" already exists; SQL statement:


H2 is supposed to be a in-memory DB, no keeping data between two startup ! Why do I receive these errors ?


Any ideas ? Thanks


Aucun commentaire:

Enregistrer un commentaire