简体   繁体   中英

Existing indexes in H2 for unit tests

I have a service that runs on a MySQL database. The service is written in Java and uses Spring & JPA/Hibernate. We are using an H2 database for the unit tests. The problem is when we run our tests, in the schema creation phase we see this error:

Index "USERNAME_INDEX" already exists; SQL statement: create index userName_index on MyTable1 (userName)

The issue seems to be that our domain classes have indexes with the same name for different tables:

MyTable : userName_index on column userName
MyTable1 : userName_index on column userName

Since we only see the error for MyTable1, our guess is that the index for MyTable is created successfully and then creating the index for MyTable1 fails.

Apparently in H2 index names must be unique per schema, but MySQL allows indexes with the same name as long as they are in different tables.

We cannot change the index names. I've also tried adding the MySQL mode to the connection URL like this:

"jdbc:h2:mem:./MyService;MODE=MySQL;DB_CLOSE_DELAY=-1;"

How can I make unit tests work with H2 with the current index names?

As of version 2.1.214, H2 expects index names to be unique per schema. I did not find this mentioned anywhere in the docs. However, I confirmed it by looking at the source code. The Schema class uses a ConcurrentHashMap to contain all of indexes related to the schema, and the names are not prefixed by a table name to make them unique per table.

I worked around this limitation by creating the tables as part of the pre-test operations (@Before method in JUnit tests). This is not ideal as I effectively bypassed the code which creates the tables automatically, but it was sufficient for my case, because I was testing a different section of the code.

Like JB Nizet mentioned, testing using a mock database like H2 has some limitations, and it is not a perfect reflection of the production environment. Whenever I need an exact production like environment, I have resorted to using containerized databases as part of my unit tests.

Hopefully this gives you new perspectives on how to handle your particular scenario, given the current limitations of H2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM