jacekn
jacekn

Reputation: 1541

How to cause SpringBoot/Hibernate to create a schema for unit testing?

Environment

SpringBoot 2 with H2 as test dependency.

Production works

Jar is deployed to cloud. A DB2 service is configured with driver and connection details, and automatically bound to the java application. There's no configuration in the jar itself. There is the application.properties file but it's empty. This part works fine and I'm hoping that a solution exists which will not require me to create property files and profiles.

Local Unit Test crashes on 'schema xxx not found'

@Entity(table="Employee", schema="acme")
class Employee {
...
}

@RunWith(SpringRunner.class)
@DataJpaTest
public class EmployeeTest {
...
}
  1. No data source configuration exists.
  2. SpringBoot sees H2 dependency and selects Hibernate by default.
  3. Hibernate sees the Entity definition and attempts to drop the table first.
  4. The drop uses the schema name drop table acme.employee if exists. No schema has been created so process fails with JdbcSQLSyntaxErrorException: Schema "acme" not found.
  5. I tried @TestPropertySource(properties ="jdbc:h2:testb;INIT=CREATE SCHEMA IF NOT EXISTS acme;") with no luck.

I've found issues like this on the web and potential solutions. But they go very far into Hibernate and/or Spring configuration files. I would really want to avoid this. It's only local unit test that fails so I'm hoping to find a solution that is contained within the test.

Upvotes: 1

Views: 2315

Answers (2)

lane.maxwell
lane.maxwell

Reputation: 5862

The absolute simplest means of doing this is to use h2 (or hsql as you are), and set ddl-auto to create-drop.

spring:
  datasource:
    driver-class-name: org.h2.Driver
    password:
    url: jdbc:h2:acme
    username: sa
  jpa:
    database-platform: org.hibernate.dialect.H2Dialect
    hibernate:
      ddl-auto: create-drop

Upvotes: 1

Uyric
Uyric

Reputation: 744

If you need a different behaviour for your tests, that's basically a different profile. Although you prefer not to define properties files, the solution below doesn't go too deep into configuration and allows you to be very explicit in your tests.

  1. Create application-test.properties (or yml if you prefer) with:
spring.datasource.url = jdbc:h2:mem:testb;init=CREATE SCHEMA IF NOT EXISTS acme;
  1. Select Spring profile in your test classes with the annotation @ActiveProfiles:
@SpringBootTest
@ActiveProfiles("test")
class MyTest {
    ...
}
  1. Give it a go. H2 should create the schema just before Hibernate tries to create the tables.

Upvotes: 2

Related Questions