vendredi 29 juillet 2016

How to mock TemporaryFile moveTo() method?

I'm trying to create a test case for the controller below but I'm encountering some issues that I believe to be related to mocking methods correctly.

Issue:

Every time my test runs through this line:

file.ref.moveTo(new File(s"${configuration.uploadFileLocation}/$filename").getCanonicalFile,true)

it throws the following error:

Error:

[info] - run test *** FAILED ***
[info]   java.lang.NullPointerException:
[info]   at java.nio.file.Files.provider(Files.java:97)
[info]   at java.nio.file.Files.move(Files.java:1392)
[info]   at play.api.libs.Files$TemporaryFile.moveTo(Files.scala:100)

Controller:

def run = Action.async(parse.multipartFormData) { implicit request =>
  request.body.file("file").map { file =>
  import java.io.File
  val filename = randomFileName
  val contentType = file.contentType
    if(contentType == Some("text/csv")) {
     file.ref.moveTo(new File(s"${configuration.uploadFileLocation}/$filename").getCanonicalFile,true)
    val result = addressApiClient.multipleMatch(filename)
    result.map(a => Ok(views.html.multipleMatch(Some(a), None, Some(filename))))
  }else {
    Future.successful(Ok(views.html.multipleMatch(None, Some("add message..."),None)))
  }
}.getOrElse {
  Future.successful(Ok(views.html.multipleMatch(None, Some("add message..."),None)))
}
}

Test case:

test("run() test") {
 val mockMessageApi    = mock(classOf[MessagesApi])
 val mockApiClient     = mock(classOf[AddressApiClient])
 val mockConfiguration = mock(classOf[Configuration])
 val mockFile          = mock(classOf[File])

 val buildFakeRequest =  FakeRequest(POST, "", FakeHeaders(), {
  val tempFile =  new TemporaryFile(mockFile)
  val filePart = FilePart("file", "test.file", Some("text/csv"), tempFile)
  MultipartFormData(Map(), List(filePart), List())
}
)

val controller = new MultipleMatch(mockApiClient, mockMessageApi, mockConfiguration)
val response   = controller.run()(buildFakeRequest)
}

Question:

How can I effectively mock the ref and the moveTo method? Please explain what is causing this to happen so I don't fall on the same issue again in the future. Many thanks

Aucun commentaire:

Enregistrer un commentaire