Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot. @DataJpaTest H2 embedded database create schema

I have couple of entities in my data layer stored in particular schema. For example:

@Entity
@Table(name = "FOO", schema = "DUMMY")
public class Foo {}

I'm trying to setup H2 embedded database for integration testing of my data layer. I'm using @DataJpaTest annotation for my tests to get H2 embedded database configured automatically. However, the creation of tables fails because schema DUMMY is not created at DB initialization.

Any ideas on how to create schema before creation of tables in test cases?

I've tried to use @Sql(statements="CREATE SCHEMA IF NOT EXISTS DUMMY") but didn't succeed.

Also, I've tried to set spring.datasource.url = jdbc:h2:mem:test;INIT=CREATE SCHEMA IF NOT EXISTS DUMMY in my test.properties file together with TestPropertySource("classpath:test.properties"), but that didn't work too.

like image 303
StasKolodyuk Avatar asked Aug 19 '16 11:08

StasKolodyuk


People also ask

How do I create a schema in h2 database?

You could run a script, or just a statement or two: String url = "jdbc:h2:mem:test;" + "INIT=CREATE SCHEMA IF NOT EXISTS TEST" String url = "jdbc:h2:mem:test;" + "INIT=CREATE SCHEMA IF NOT EXISTS TEST\\;" + "SET SCHEMA TEST"; String url = "jdbc:h2:mem;" + "INIT=RUNSCRIPT FROM '~/create.

What is the use of @DataJpaTest?

@DataJpaTest is used to test JPA repositories. It is used in combination with @RunWith(SpringRunner. class) . The annotation disables full auto-configuration and applies only configuration relevant to JPA tests.


2 Answers

I had the same issue, I managed to resolve by creating schema.sql (in resources folder) with the content

CREATE SCHEMA IF NOT EXISTS <yourschema>

Documentation can be found here but imho the lack of real examples make it very complex. Warning: this script is also executed within the normal (not test) environment.

Not mandatory, but good practice, add h2 dependency only in test scope

<dependency>    <groupId>com.h2database</groupId>    <artifactId>h2</artifactId>    <scope>test</scope> </dependency> 
like image 64
David Canós Avatar answered Sep 21 '22 19:09

David Canós


I think you are looking for this annotation:

@AutoConfigureTestDatabase(replace=Replace.NONE)

example:

@DataJpaTest
@AutoConfigureTestDatabase(replace= AutoConfigureTestDatabase.Replace.NONE)
class UserRepoTest {...}
like image 45
MonirRouissi Avatar answered Sep 20 '22 19:09

MonirRouissi