Robert Strauch
Robert Strauch

Reputation: 12906

Using Spring repository in static methods for setting up test data

In order to setup test data for my Spring Boot integration tests, I'd like to create some helper classes and methods which populate the data using the repositories.

Here is an example:

@Component
public class TestUtils {

    private static TemplateRepository templateRepository;

    @Autowired
    public TestUtils(TemplateRepository templateRepository) {
        TestUtils.templateRepository = templateRepository;
    }

    public static void createTemplates() {
        Template template = Template.builder()
                .content("some content")
                .build();

        templateRepository.save(template);
    }
}

Due to a lack of experience, I cannot tell if this approach is fine. It it "safe" to inject the repository as static? Or are there better approaches for setting up test data?

Upvotes: 0

Views: 1727

Answers (3)

Wim Deblauwe
Wim Deblauwe

Reputation: 26878

Don't use static. If you want to use Java to initialize the data in the repository, just do so in your test.

What you can do if you need to create a few things in different repositories is create a dedicated component:

@Component
public class DatabaseInitializer {

  private final TemplateRepository templateRepository;
  private final MyOtherRepository myOtherRepository;

 // Add constructor here

  public void createInitialData() {
    // Use repositories to persist some data
  }
@ExtendWith(SpringExtension.class)
@Import(DatabaseInitializer.class)
class MyTest {
  @Autowired
  private DatabaseInitializer initDb;

  @Test
  void myTest() {
    initDb.createInitialData(); // Or put this in a `@Before..` method
    // actual test here
  }
}

Upvotes: 2

Saurabh Singh
Saurabh Singh

Reputation: 218

There is a very well explained process to initialize the data in docs. I would advice you to refer below

https://docs.spring.io/spring-boot/docs/current/reference/html/howto.html#howto.data-initialization

You just have to manintain Insert statements in predefined sql files.

Upvotes: 0

jden
jden

Reputation: 2288

I use TestContainers and Flyway. You can make SQL scripts and annotate test methods with @Sql and provide a .sql file and/or statements to be run. You can store these .sql files in the test/resources folder.

Loading Initial Test Data

Upvotes: 1

Related Questions