Test cases for file upload using akka-http in Scala


Hello folks,

In my previous blog, i explained how to upload a file using akka-http in Scala. Later, i got the queries about the test cases for the same. Therefore, in this blog I am going to explain the way of writing test cases for file upload.

First we need to add test dependency :


"com.typesafe.akka" %% "akka-http-testkit" % "2.4.3",
"org.scalatest" %% "scalatest" % "2.2.6" % "test"

Full code :

package com.rishi

import java.io.File

import akka.http.scaladsl.model.{StatusCodes, Multipart, ContentTypes}
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.{FlatSpec, Matchers}

class FileUploadSpec extends FlatSpec with Matchers with ScalatestRouteTest with FileUpload {
  override def testConfigSource = "akka.loglevel = WARNING"

  "File upload" should "not be able to upload file when file does not exist" in {
    val file = new File("")
    val formData = Multipart.FormData.fromFile("file", ContentTypes.`application/octet-stream`, file, 100000)
    Post(s"/user/upload/file", formData) -> routes -> check {
      status shouldBe StatusCodes.InternalServerError
      responseAs[String] shouldBe "Error in file uploading"
    }
  }

  it should "be able to upload file" in {
    val file = new File(getClass.getResource("/testFile").toString)
    val formData = Multipart.FormData.fromFile("file", ContentTypes.`application/octet-stream`, file, 100000)
    Post(s"/user/upload/file", formData) -> routes -> check {
      status shouldBe StatusCodes.OK
      responseAs[String] contains  "File successfully uploaded"
    }
  }
}

Get full code here.

It’s done. Hope you enjoy it. In my next blog, I will create a basic application to handle multipart formdata (file + form fields) using akka-http in Scala. So Stay tuned !!

Happy Blogging !!!

Advertisements

About Rishi Khandelwal

Sr. Software Consultant having more than 6 years industry experience. He has working experience in various technologies such as Scala, Java, Play, Akka, Spark, Hive, Cassandra, Akka-http, ElasticSearch, Backbone.js, html5, javascript, Less, Amazon EC2, WebRTC, SBT
This entry was posted in Scala. Bookmark the permalink.

3 Responses to Test cases for file upload using akka-http in Scala

  1. Pingback: A basic application to handle multipart form data using akka-http with test cases in Scala | Knoldus

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s