1

我在 Grails 中编写了一个控制器,它接受多部分请求(xml+binary file1+binary file2+...)。如何对该控制器进行单元测试?如何在单元测试中设置请求的内容?任何示例代码表示赞赏!

4

3 回答 3

6

我正在使用 Grails 2.4,您可以在单元测试中简单地使用GrailsMockMultipartFilerequest.addFile方法。

此代码适用于带有 Spock 测试框架的 Grails 2.4.4:

控制器端:

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

单元测试端:

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

}
于 2014-12-04T16:19:19.970 回答
2

我们正在使用 Spock,我们的代码如下所示:

def mockFile = new MockMultipartFile(Constants.PARAM_DA_FILE, 'filename.xls', 'application/vnd.ms-
excel', articleFile.bytes)
params.(Constants.PARAM_DA_FILE) = mockFile
controller.request.addFile(mockFile)
于 2012-12-01T16:11:56.780 回答
2

我从:http ://roshandawrani.wordpress.com/2011/02/03/grails-mock-testing-a-file-upload/ 得到它,它正在工作。这是示例:

import org.springframework.mock.web.MockMultipartFile
import org.springframework.mock.web.MockMultipartHttpServletRequest

class FileUploadControllerTests extends grails.test.ControllerUnitTestCase
{
    void testFileUpload()

    {

        def imgContentType = 'image/jpeg'

        def imgContentBytes = '123' as byte[]
        ....
        ....

        controller.metaClass.request = new MockMultipartHttpServletRequest()
        controller.request.addFile(
        new MockMultipartFile('image', 'myImage.jpg', imgContentType, imgContentBytes)       )
        ....
        controller.save()
        assertEquals HttpServletResponse.SC_OK, controller.response.status
        ....

    }
}
于 2012-12-02T19:42:40.383 回答