Java – spring MVC – use flyway to clean up the database between tests
I use flyway to manage the database state in my spring MVC application
I configure it in my servlet context XML file exactly as recommended in their docs
<bean id="flyway" class="org.flywaydb.core.Flyway" init-method="migrate"> <property name="dataSource" ref="..."/> ... </bean> <!-- The rest of the application (incl. Hibernate) --> <!-- Must be run after Flyway to ensure the database is compatible with the code --> <bean id="sessionFactory" class="..." depends-on="flyway"> ... </bean>
I want to do two things in JUnit testing –
>Once before all tests, delete and recreate the database and let it migrate again This creates a clean database for each test suite. > Clean up all database tables before each test In other frameworks (such as rspec / rails), I do this by running DB statements through transactions, so they roll back at the end of the test I'm not sure what the best practices are in the spring MVC world
I don't know where to start implementing the above content, so any guidance is appreciated
thank you!
Solution
First, you can clean up the database before each test, as follows:
@Autowired Flyway flyway; @Before puublic void init(){ flyway.clean(); flyway.migrate(); }
Second, you can use jdbctestutils to delete all rows in the table Please find doc: JDBC test support here https://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html
You can also use @ rollback and @ commit to run test methods in a transactional manner