Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a controller that takes in a file as part of the parameter. I'm wondering how can I test this?

my controller action:

def save () {
  def colorInstance = new Color(params.color)
  CommonsMultipartFile file = request.getFile('color.filename')
  fileUploadService.upload(colorInstance, file, "foldername")
  if (requestInstance.save(flush: true)) {
    withFormat {
      html {redirect(action: "list") }
      js {render "test"}
    }
  }
}

I've started with something like this:...

import org.junit.Before
import grails.test.mixin.Mock
import grails.test.mixin.TestFor

@TestFor(ColorController)
@Mock(Color)
class ColorControllerTests {

    @Before
    void setUp() {
        controller.fileUploadService = new FileUploadService
    }
}

Question

  • I can't figure out how to test the CommonsMultipartFile for file upload.
  • Also, this test case will sit in unit test folder. How can I execute it?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
945 views
Welcome To Ask or Share your Answers For Others

1 Answer

I am using Grails 2.4, and you can simply use GrailsMockMultipartFile and request.addFile method in your unit test.

This code works on Grails 2.4.4, with Spock testing framework:

Controller side:

class FileUploadController {

    def upload() {
        def multipartFile = request.getFile('requestParamName')
        if (multipartFile.empty) {
            flash.message = 'Error: file cannot be empty'
            render(view: 'upload')
            return
        }

        // do something now with your file
    }
}

Unit test side:

import grails.test.mixin.TestFor
import org.codehaus.groovy.grails.plugins.testing.GrailsMockMultipartFile
import spock.lang.Specification

@TestFor(FileUploadController)
class FileUploadControllerSpec extends Specification {

    void "upload should add flash error message if empty file in request"() {
        given:
        def multipartFile = new GrailsMockMultipartFile('requestParamName', 'someExcelFile.xls', 'application/vnd.ms-excel', new byte[0])
        request.addFile(multipartFile)

        when:
        controller.upload()

        then:
        assertEquals('Error: file cannot be empty', flash.message)
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...