How to do Unit testing using embedded PostgreSQL in Akka

Table of contents
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:

https://www.techhub.knoldus.com/dashboard/projects/akka/60db2e45397f83a01374c34f

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:

columndatatype
student_idVARCHAR
emailVARCHAR
nameVARCHAR
date_of_birthTIMESTAMP
marksJSON
addressJSON

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
    .builder()
    .setPort(5332)
    .start()

  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()
  flyway.setDataSource(server.getDatabase(USER_NAME,DB_NAME))
  val path: String = System.getProperty("user.dir")
  //path for SQL file
  flyway.setLocations(s"filesystem:$path/src/test/resources/db.migration")   
  flyway.migrate()
}

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

 def checkIfStudentExists(id: String): Future[Int] = {
    db.run(
      studentsQuery
        .filter(col =>
          col.email === id ||
            col.studentId === id)
        .size
        .result)
  }

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:

https://www.techhub.knoldus.com/dashboard/projects/akka/60db2e45397f83a01374c34f

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading