How to fake ENUM columns in the H2 database for play unit testing?

匆匆过客 提交于 2019-12-04 14:06:25
Eike D

Here a workaround that works for spring-boot with H2 - it doesn't depend on either though, so you can do something similar for play.

Please note that this is a fake and doesn't really allow you to test enums fully but it allows you to run tests against a pre-existing production DBs (where you cannot just go and change the schema) without having to write the entire DDL yourself.

So, instead of letting your test framework setup the connecting string for the in-memory db, do configure the H2 connection string yourself.

Here how the magic setting looks in my case:

# the next line is very important it names the ddl work
# H2 does not support enums
# In order to fake support for them we have to declare a
# domain called enum and mapped it to a varchar - the size
# I picked at random but it is "good enough" for now.
# H2 will run this before hibernate creates the schema and
# then the schema creation will succeed
spring.datasource.url=jdbc:h2:mem:test;MODE=MySQL;INIT=CREATE DOMAIN IF NOT EXISTS enum as VARCHAR(255);DB_CLOSE_ON_EXIT=FALSE

The magic is this:

CREATE DOMAIN IF NOT EXISTS enum as VARCHAR(255)

this tells H2 to treat the custom (domain) datatype enum as varchar - you can obviously change the size to whatever.

It as done as an INIT cause that makes sure it is executed before the first bit of ddl is executed against it by any framework

So, in case of Play! the setting would be db.default.jdbcUrl - or however you define your test database connection (e.g. as a trait)

niels

Normally JPA translate it for you into an basic-type. See Map enum in JPA with fixed values? or JPA Enum ORDINAL vs STRING. I think this is the only way to become database independent.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!