Search code examples
unit-testingjunitliquibase

take liquibase scripts not from resource folder during unit tests


I have a following project structure

bin
  start.sh
db
  liquibase_scripts
    ...
    schema.json
main
  java
    ...
test
  resources
    liquibase_scripts
      ...
      schema.json

So than I build my project, folder db with liquibase scripts added to distributive. In unit tests I use H2 database and want to load schema from db/liquibase. I create bean

    @Bean
    public SpringLiquibase springLiquibase() {
        SpringLiquibase springLiquibase = new SpringLiquibase();
        springLiquibase.setDataSource(dataSource());
        springLiquibase.setChangeLog("classpath:/liquibase/sam.json");
        return springLiquibase;
    }

The problem is that method setChangeLog look at resource folder in test folder. So to solve the problem I copied all liquibase scripts to the test/resources directory. But this is not ok becouse now I have 2 copies of scripts in different folders.

Is there a way to force springLiquibase.setChangeLog find scripts in any folder not only in test/resources?


Solution

  • In Maven build configuration you can define testResources, which may be directories and files. It looks like this:

    <build>
        <testResources>
            <testResource>
                <directory>${project.basedir}/db/liquibase_scripts</directory>
            </testResource>
        </testResources>
    </build>
    

    With such configuration Maven copies the files into the target/test-classes directory. Thanks to that those files can be used as test resources in the code, but there's no duplication in the project files.

    Im using such configuration (Liquibase + testResources) in one of my projects. To better reproduce your problem, I've created a separate branch, where you can find the configuration described above - see: this commit diff. All test pass after the change.