unit testing with in-memory database [duplicate]

让人想犯罪 __ 提交于 2019-12-23 09:33:58

问题


I have PostgreSQL database. It is used for unit testing.

  • I want to speed the tests up so I want to use some kind of in-memory databases (e.g. H2).
  • I want to dump the database (from PostgreSQL) and the import such a dump into in-memory database.

Do you have any suggestion concerning in-memory database choice? I want that database to be compatible with PostgreSQL.


回答1:


I'd simply create a database directory (called a cluster in PostgreSQL) in tmpfs (essentially a RAM-disk - /dev/shm is configured as such in most Linux distributions) and simply run postgres there on non-standard port, for example like this:

initdb -D /dev/shm/pgtest
postmaster -D /dev/shm/pgtest -p 11111



回答2:


I would recommend using HSQL with a spring combination. I was brought on to my current occupation to do this exact thing, and even though it is a headache, it can be done. And based on quick research, it appears hsql is compatible with PostgreSQL. Let me know if you have any other questions.




回答3:


Do you need to drop Pg for this?

If you're unit testing against a different database than you run against in production your tests just won't be as good.

Try this: Optimise PostgreSQL for fast testing .

... and see how you go.

update: You might think putting everything on a ramdisk will make your tests massively faster, but you're probably mistaken. It's often more efficient to let data that isn't in use spill to disk so the system can use more RAM for the task at hand. Using unlogged tables and proper async commit or (for testing only, will eat your data) fsync=off should get you very similar speeds.

If you really require a true in-memory tables, create a file system on a ramdisk or tmpfs and initdb a new cluster in there. You might as well use UNLOGGED tables so they don't go through the write-ahead log.

Note that while tmpfs is a ramdisk, it allows less-used pages to go to swapspace. If you absolutely must have all the data pinned in RAM for some reason, you'll need to use the ramdisk driver and create a file system on a ramdisk instead. My advice: don't do it. Just configure Pg properly for fast testing.



来源:https://stackoverflow.com/questions/11764487/unit-testing-with-in-memory-database

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