12

I'm testing a controller that returns a json response but the tests fail after the first time because the h2 database does not reset the auto increment id. Using fixtures or creating objects manually has a same problem.

@Before
public void setUp() {
    Fixtures.deleteAllModels();
    Fixtures.loadModels("data.yaml");
}

How to solve this problem?

3 Answers 3

26

Start your play app, fire up browser with this url (if you run play app locally):

http://localhost:9000/@db

Enter your h2 db, and type the command below and run:

ALTER TABLE <table_name> ALTER COLUMN <column_name> RESTART WITH 1

If you'd like to do this programmatically, Fixtures.executeSQL() might be useful

For more information, check http://www.h2database.com/html/grammar.html#alter_table_alter

5

If you are using Spring, I found this blog post which suggests using @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)

So that each test uses a new application context, thereby resetting the db increments.

1
  • 13
    This will make the tests super slow
    – avmohan
    Mar 14, 2018 at 7:04
2

Execute an SQL-script on your table:

TRUNCATE TABLE my_table RESTART IDENTITY;
ALTER SEQUENCE my_table_id_seq RESTART WITH 1;

H2 should be of version 1.4.200 or higher.

See https://www.h2database.com/html/commands.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.