Search code examples
javajunith2in-memory-database

How to drop H2 database between each test class when running with GRADLEW BUILD?


Folks,

Please assist me in below enlisted queries-

I'm doing JUnit testing using H2 database. I'm testing for Signup and login. So, in this both case I need to create user that I have created in my @BeforeClass in each test class. Now, when I'm running single class test cases, it is working fine (Reason is: It creates user performs the test cases and deleted automatically since I'm using H2 DB). But when I'm running gradlew build it gets failed after first test class. It gives me error "data.helper.ErrorException: User Id must be unique." Any help will be appreciated regarding how to drop the database between each class.

Thanks


Solution

  • You can use DbUnit library to handle your problem in convenient way. Populate database before test case and clear it after. See http://dbunit.sourceforge.net/howto.html.

    Pay attention to create H2 database configuration string. Database must alive until JVM shutdown. jdbc:h2:mem:test;DB_CLOSE_DELAY=-1