swateek
swateek

Reputation: 7580

Functional Test: Upload File via REST API in Grails

I am preparing Functional Test cases for my RESTful API project, using the functional test plugin of Grails.

I am unable to upload a file using the technique that works for everything else in my case.

class CreateFunctionalSpec{

final String CREATE_API = '/document-file'

def "Upload Document to temporary location"() {

  File nfile = new File('test/test-data/myfile.jpg')
  nfile.createNewFile()

   when:
   post("$RESTFUL_API_BASE_URL${CREATE_API}") {
       headers['Accept'] = 'application/json'
       headers['Authorization'] = authHeader()
       body{
            "file:nfile"    
       }
   }


   then:
        assert file
}}

I am unsure how to place a file in the body, I have tried adding it as parameter but nothing works.

Upvotes: 0

Views: 322

Answers (1)

vicky
vicky

Reputation: 2149

This code works !!!

   def "Upload Document to temporary location"() {

    setup:
    def testDocument = new File('test/test-data/test-document.jpg')

    when:
    post("$RESTFUL_API_BASE_URL${BDM_CREATE_API}") {
        headers['Accept'] = 'application/json'
        headers['Authorization'] = authHeader()
        body{
            setProperty("file",testDocument)
        }
    }
    then:
    201 == response.status
    def jsonData = JSON.parse response.text
    jsonData["status"]=="Success"

}

Upvotes: 1

Related Questions