Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embedded PostgreSQL for Java JUnit tests

Is there an embedded PostgreSql so that we could unit test our PostgreSql driven application?

Since PostgreSql has some dialects, it's better to use embedded PostgreSql itself than other embedded databases.

Embedded does not necessarily mean it must be embedded in the JVM process. It also does not necessarily need to use in-memory persistence. It should be loaded automatically by the dependency management (Maven, Gradle), so that Unit tests can run on every machine without having to install and configure a local PostgreSQL server.

like image 902
blue123 Avatar asked Jan 14 '13 06:01

blue123


People also ask

Can Postgres be embedded?

PostgreSQL is feature rich, has great SQL support, and is a great choice as the database to embed in your software or hardware products.

What is Postgres Java?

PostgreSQL (which goes by the moniker Postgres) is famous for its object-relational nature. In contrast, other database systems are usually relational. Due to its nature, it's a great pairing with Java, which is heavily object-oriented.

How do I view tables in PostgreSQL?

Use the \dt or \dt+ command in psql to show tables in a specific database. Use the SELECT statement to query table information from the pg_catalog. pg_tables catalog.


2 Answers

The is an "embedded" PostgresSQL server that has been designed for unit testing from Java:

https://github.com/yandex-qatools/postgresql-embedded

Embedded postgresql will provide a platform neutral way for running postgres binary in unit tests. Much of the code has been crafted from Flapdoodle OSS's embed process

As an aside, there also exists similar projects for Mongo, Redis, Memcached and nodejs.

like image 105
btiernay Avatar answered Sep 24 '22 06:09

btiernay


No, there is no embedded PostgreSQL, in the sense of an in-process-loadable database-as-a-library. PostgreSQL is process oriented; each backend has one thread, and it spawns multiple processes to do work. It doesn' make sense as a library.

The H2 database supports a limited subset of the PostgreSQL SQL dialect and the use of the PgJDBC driver.

What you can do is initdb a new temporary database, start it with pg_ctl on a randomized port so it doesn't conflict with other instances, run your tests, then use pg_ctl to stop it and finally delete the temporary database.

I strongly recommend that you run the temporary postgres on a non-default port so you don't risk colliding with any locally installed PostgreSQL on the machine running the tests.

(There is "embedded PostgreSQL in the sense of ecpg, essentially a PostgreSQL client embedded in C source code as preprocessor based C language extensions. It still requires a running server and it's a bit nasty to use, not really recommended. It mostly exists to make porting from various other databases easier.)

like image 35
Craig Ringer Avatar answered Sep 26 '22 06:09

Craig Ringer