2

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

PySaad
  • 1,052
  • 16
  • 26

5 Answers5

1

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

Interlated
  • 5,108
  • 6
  • 48
  • 79
fxrbfg
  • 1,756
  • 1
  • 11
  • 17
0

You can add an @Before method in each test that truncates the tables. This helps to avoid sideeffects of tests in a single test class, too.

@Before
public void truncateTables() {
    //truncate tables
}
Stefan Birkner
  • 24,059
  • 12
  • 57
  • 72
0

You should use @Before instead of @BeforeClass so that the set up code is run before each test method rather than once for the entire class. You can also add an @After method to perform any clean up after each test method.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
0

If you are using spring boot, refer to this stack overflow question.

The class annotation @DirtiesContext will cause the context to be dropped between each test case

@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)

Interlated
  • 5,108
  • 6
  • 48
  • 79
0

If you are using jdbi2 framework then you can use similar method to clear H2 database objects between tests:

public class H2JDBIRule extends ExternalResource {

    private Handle handle;

    //...

    public void dropDatabase() {
        handle.begin();
        handle.execute("DROP ALL OBJECTS");
        handle.commit();
    }

    //...

}

Just make sure that you reference it in your Test case class like this:

@ClassRule
public static H2JDBIRule rule = new H2JDBIRule();

@After
public void tearDown(){
    rule.dropDatabase();
}
zygimantus
  • 3,649
  • 4
  • 39
  • 54