在Grails集成测试用例中模拟CommonsMultipartFile

时间:2015-04-14 12:29:02

标签: grails integration-testing spock

我有一个服务方法,它接受CommonsMultipartFile并将其上传到服务器

class ExampleService() {
    def saveFile(CommonsMultipartFile file) {
        // some validation code for file
    }
}

尝试同时使用MockMultipartHttpServletRequestGrailsMockMultipartFile

如果MockMultipartHttpServletRequest收到错误:

|  org.codehaus.groovy.runtime.typehandling.GroovyCastException: 
Cannot cast object 'org.springframework.mock.web.MockMultipartFile@2f39360' 
with class 'org.springframework.mock.web.MockMultipartFile' to 
class 'org.springframework.web.multipart.commons.CommonsMultipartFile'

GrailsMockMultipartFile错误相同:

|  org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot 
cast object 'org.codehaus.groovy.grails.plugins.testing.GrailsMockMultipartFile@1022f0bd' 
with class 'org.codehaus.groovy.grails.plugins.testing.GrailsMockMultipartFile' to 
class 'org.springframework.web.multipart.commons.CommonsMultipartFile'

提到了stack overflow question

我应该如何模拟CommonsMultipartFile并将其作为参数传递给我的测试用例?


解决方案

我找到了解决方案,请查看我的answer

2 个答案:

答案 0 :(得分:1)

在经历了不同的堆栈溢出链接和CommonsMultipartFile JDK后,我想出了这个解决方案

如果我使用错误的方法@burtbeckwith

,请告诉我
File getTestFile(String fileName = "") {
    //Code which create file instance 
}

// Inside my test case I have created CommonsMultipartFile test file and used it.
DiskFileItemFactory factory = new DiskFileItemFactory()
FileItem fileItem = factory.createItem( "file", "multipart/form-data", false, "logo.png" )
IOUtils.copy(new FileInputStream(getTestFile()), fileItem.getOutputStream())
CommonsMultipartFile testFile = new CommonsMultipartFile(fileItem)

答案 1 :(得分:1)

如果您更改saveFile(CommonsMultipartFile)方法以接受接口MultipartFile的实例而不是特定实现,则更容易进行模拟,您将不会失去任何功能。

saveFile(MultipartFile)