Use the PostgreSQL maven plugin, which is designed for the purpose.
You'll need to tell it where PostgreSQL's binaries are if it can't find them on the PATH.
If you want to roll your own you'll need to:
- Invoke
initdb via ProcessBuilder to create a temp data directory.
- Make any necessary changes to
pg_hba.conf or generate a new one
- Invoke
postgres via ProcessBuilder to start PostgreSQL
Your ProcessBuilder must set up the PATH environment variable so PostgreSQL can find its other binaries.
You don't have to generate a custom postgresql.conf, as you can just pass parameters on the command line, e.g.
postgres -D some-datadir -c port=5599 -c listen_addresses='127.0.0.1'
etc. But if you want, you can just append a single line to the default postgresql.conf like
include 'myapp-test.conf'
then generate/copy a myapp-test.conf file containing all the PostgreSQL config settings you want. This can be easier if you have lots of settings and/or complex ones due to command line length limits, and it can be more readable/debuggable.
Do not use the default port when starting PostgreSQL for testing. Always override the port.
initdbandpostgrescommands viaProcessBuilderetc. Pretty easy really.