gpt4 book ai didi

grails - Grails集成测试案例中的Mock CommonsMultipartFile

转载 作者:行者123 更新时间:2023-12-02 14:31:02 25 4
gpt4 key购买 nike

我有一个接受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

最佳答案

经过不同的堆栈溢出链接和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)

关于grails - Grails集成测试案例中的Mock CommonsMultipartFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29627354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com