net.sixpointsix:spring-boot-data-fixture

Spring boot data fixtures


Keywords
database, fixture-loader, fixtures, spring-boot
License
MIT

Documentation

Spring Boot Data Fixtures

CircleCI CodeFactor

Setting up test data can be difficult when you need different data for each environment. The Spring Boot Data Fixtures library allows this data to be set up in each environment with standard Spring Beans.

Installing from Maven Central

<dependency>
  <groupId>net.sixpointsix</groupId>
  <artifactId>spring-boot-data-fixture</artifactId>
  <version>1.1.0</version>
</dependency>

Adding data

Lets imagine you need to add some roles to your database

@Configuration
class AppConfiguration {

    @Bean
    public FixtureFunctionSet<Role> setUpRoles(RoleRepository roleRepository) {
        return FixtureFunctionSet
                .<Role>builder()
                .setShouldApply(r -> !roleRepository.has(r.getName()))
                .setRun(roleRepository::save)
                .addEntity(new Role("ROLE_USER"))
                .addEntity(new Role("ROLE_ADMIN"))
                .build();
    }
}

So whats happening here? We have a bean that depends on a RoleRepository, that could be any type of repository (JPA, JDBC, Api call) as long as there is a way to test if the data is there.

There is a test to see if the role needs to be added

.setShouldApply(r -> !roleRepository.has(r.getName()))

In this case we just check that the RoleRepository does not have a role with this name but it could be anything. If that method returns false nothing else will happen.

If the should apply method returns true it will call the run method.

.setRun(roleRepository::save)

This is calling the same method to set up the data.