How to do Unit testing using embedded PostgreSQL in Akka

Reading Time: 2 minutes

Embedded PostgreSQL provides a platform neutral way for running PostgreSQL binary in unit tests. It is an efficient database to write test cases as it supports all data types of PostgreSQL.

In this blog I will not dive deep in the features of Embedded PostgreSQL but rather focus on it’s integration with an Akka application. I have added a sample project for the better understanding.

Database testing sample:

To start with test cases the first step is to add it’s library.

"com.opentable.components" % "otj-pg-embedded" % "0.13.3" % Test

Let’s start by assuming we have a student table with following details:


The next step is to create tables to execute test cases. In order to do that we have to add a create table query in a sql file and configure it with the Embedded PostgreSQL.

trait ConfigLoader extends LazyLogging {

  val server: EmbeddedPostgres = EmbeddedPostgres

  implicit val schema: String = SCHEMA_NAME
  val driver = PostgresProfile
  import driver.api.Database
  implicit val db: Database = Database.forURL(url = server.getJdbcUrl(USER_NAME,DB_NAME),
    driver = "org.postgresql.Driver")

  private[this] val flyway = new Flyway()
  val path: String = System.getProperty("user.dir")
  //path for SQL file

After doing the configuration, you are good to write test cases for database operations.

 def checkIfStudentExists(id: String): Future[Int] = {
        .filter(col =>
 === id ||
            col.studentId === id)

I have added a method with slick query to check if student is valid/ Invalid. Below is the test case for the above method.

class StudentsDAOSpec extends AsyncWordSpecLike with ScalaFutures with Matchers with ConfigLoader {

  implicit val defaultPatience: PatienceConfig =
    PatienceConfig(timeout = Span(5, Seconds), interval = Span(500, Millis))

  val studentsDAO = new StudentsDAO()

  "StudentsDAO" should {

    "able to check if student exits" in {
      whenReady(studentsDAO.checkIfStudentExists("id")) { res =>
        res shouldBe 0


So, this was an overview of how to integrate embedded PostgreSQL in your Akka project to test database operations.

For better understanding please check database testing sample:

Leave a Reply