Spring boot and Flyway: Clear database data before integration tests

Samurai Girl :

I'm building a REST service using Spring boot framework (v2.0.2), where I have integration tests running on a database. I googled a lot and there is a sea of articles about cleaning database before tests, but unfortunately I find them either inefficient or a hack and not for Spring boot. Could you, please, bear with me and suggest a good way for this problem?

Ideally, I think the database should be cleared not before each test, but before some group of them, like suite or maybe each test class. One of the found suggestions looks like this:

@Autowired
protected Flyway flyway;

@Before
public void init() {
    flyway.clean();
    flyway.migrate();
}

which rebuilds database before each test and clearly is not efficient. Changing this to static context and using @BeforeClass does not work as Spring does not inject static fields.

Is there some nice way to reach this flyway bean from static context, to make this solution work?

Sub-question here: Flyway has a command clean, which not only clears data, but drops everything and then migrate command performs migrations again. This also seems like overhead. As the migrations are checked at startup anyway, I don't see the necessity to tear down and rebuild everything before each test group. Just clearing data would be sufficient. Would you give some advice about how this can be achieved?

To sum up, I'm looking for a standard way of removing the database data (and not tables if possible) before each group of integration tests (e.g. per class). I suppose everybody faces this task while using Spring boot, so maybe there is some nice solution considered in the framework itself.

Thank you!

evkm :

You could create configuration file for your tests. It would run one time before all tests.

@Configuration
public class TestConfig {
@Bean
public FlywayMigrationStrategy clean() {
    return flyway -> {
        flyway.clean();
        flyway.migrate();
    };
}
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=475685&siteId=1