Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

unit testing - How to test file upload in Grails

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

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

1 Reply

0 votes
by (71.8m points)

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)
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...