简体   繁体   中英

How to write unit tests with H2 in-memory database

my question might be a little bit strange but I do not really know how to write unit tests for my already existing application ( I know I should first write the unit tests and afterwards the main souce code ).

My application consists of some tables that will be created automatically from my Java classes. My production database is PostgreSQL.

Now, I want to write some unit tests with my H2 database. However, I use some data types ( some special annotation - date/time ) that are not supported by H2.

Should I write now the wrong model classes new in my test package with the correct data types so that H2 is able to create the tables? Or is there some other approach that I do not know of?

Thank you very much for your help and hints in advance!

Pitty to see your question downvoted without any discussion as to why. Do others think it unclear or insufficiently fleshed out? Hard to say.

I'd like to suggest that writing incorrect model classes so that H2 can stand in for Postgress is a bad idea. It would likely result in an impedence mismatch between the test suite and the production code that would be hard to maintain. More to the point tests based on incorrect models might not be testing anything useful. They might be tutologically exercising the database rather than the models or anything important about the application. As a final point, let's say you or someone else wanted to enlist the tests for performance benchmarking at some point down the road; tests using incorrect models against the wrong dbms would would be of no use.

I prefer to stick with the same dbms throughout the pipeline -- dev, test, staging, prod, etc. I know it's not uncommon to use different databases in certain places for the sake of speed or due to licensing concerns, but if I don't have to do it, I won't. In your case I can think of a few options.

  1. Embeded Postgress. I've seen several projects for embedding Prostgres. Look around, try a few, stick with whichever seems a good fit.

  2. Try a RAM Disk or tmpfs . Linux can create memory-based filesystems; create one, mount it and let Postgres use it. Do some testing to see if it actually provides significant perfmance benefits. Other operating systems might have similar abilities.

  3. Use standard Postgress. Run tests on a standard installation of Postgress; in other words, nothing fancy, no premature optimization, merely take the easiest, most direct path. This is what I would do.

  4. Replace Postgres with H2... but don't. I use both H2 and Postgress and I like them both, but you're already using Postgres in prod, so there is no good reason to change.

Best of luck.

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