Categories
Java

How to write Java Postgres JDBC JUnit Test

Postgres is one of the leading open-source RDBMS for developing applications using Java. As now development involves more and more TDD, we need to write Junit tests that can run independently on any build environment without the dependency on any required Database engine.

For the Postgres database, I found one very handy Java lib that can be used to mock the Postgres database in a few lines.

otj-pg-embedded is an embedded version of the Postgres database, for running this you may need to install the required MFC run time.

This can be referenced in Gradle project using following

testImplementation group: 'com.opentable.components', name: 'otj-pg-embedded', version: '0.13.3'

After this you can create one abstract base class as given below

import com.opentable.db.postgres.embedded.EmbeddedPostgres;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

public abstract class EmbeddedPG {
    // connecting to a running Postgres and feeding up the database
    public static Connection conn;

    @BeforeAll
    public static void initiPG() throws IOException, SQLException {
        EmbeddedPostgres pg = EmbeddedPostgres.start();
        conn = pg.getPostgresDatabase().getConnection();
    }

    @AfterAll
    public static void stopPg() throws SQLException {
        // close db connection
        conn.close();
    }
}

EmbeddedPostgres pg = EmbeddedPostgres.start();

The above line will download and install embedded distribution of the Postgres database for the underlying platform and start the DB engine.

Now you can extend your child’s test classes to write test cases using the Java Connection object.

For example, if you need to pass connection object in any method.

@Testable
public class PgDbInitializerTests extends EmbeddedPG {
    @Test
    public void test_init_db_ok() throws Throwable{
        DbInitializer db= DbInitializers.getInstance(StoreType.POSTGRES, this.conn, "event");
        Assertions.assertNotNull(db);
        db.initialize();
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.