【问题标题】:Mock CommonsMultipartFile in Grails integration test caseGrails集成测试用例中的模拟CommonsMultipartFile
【发布时间】:2023-03-08 05:09:01
【问题描述】:

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

【问题讨论】:

  • 能不能把saveFile()方法改成使用接口MultipartFile而不是具体实现?如果是这样,它应该更容易模拟。
  • 正如@cjstehno 所说,尽可能使用接口,例如在这种情况下,ListMap 而不是 ArrayListHashMapMultipartFile。仅在实例化和访问不在接口中的方法时使用实现类名
  • @cjstehno 将您的评论转换为答案,以便我们对其进行投票
  • 感谢你们这么快的反应。 saveFile() 方法执行一些额外的代码而不是保存文件。我不想更改我现有的方法实现。
  • @LaxmiSalunkhe - 您不会通过使用该接口来更改您的实现。它仍然是传入的相同实现。如果您的代码需要特定的实现,您可能需要研究重构以删除特定的依赖关系。该 API 非常强大,无需使用特定的实现类。

标签: grails integration-testing spock


【解决方案1】:

经过不同的堆栈溢出链接和CommonsMultipartFileJDK 我想出了这个解决方案

如果我使用了错误的方法@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)

【讨论】:

    【解决方案2】:

    如果您将saveFile(CommonsMultipartFile) 方法更改为接受接口MultipartFile 的实例而不是具体的实现,它将更容易模拟并且您应该不会丢失任何功能。

    saveFile(MultipartFile)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-13
      • 1970-01-01
      • 2012-04-25
      • 1970-01-01
      • 2023-03-31
      相关资源
      最近更新 更多