我在Grails中编写了一个控制器,它接受多部分请求(xml +二进制文件1 +二进制文件2 + ...)。如何对该控制器进行单元测试?如何在单元测试中设置请求的内容?欢迎任何示例代码!
答案 0 :(得分:5)
我使用的是Grails 2.4,您只需在单元测试中使用GrailsMockMultipartFile
和request.addFile
方法。
此代码适用于Grails 2.4.4,Spock测试框架:
控制器端:
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)
}
}
答案 1 :(得分: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)
答案 2 :(得分: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
....
}
}