如何在 Grails 中测试文件上传 [英] How to test file upload in Grails

查看:21
本文介绍了如何在 Grails 中测试文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器,它接收一个文件作为参数的一部分.我想知道我如何测试这个?

I have a controller that takes in a file as part of the parameter. I'm wondering how can I test this?

我的控制器操作:

def save () {
  def colorInstance = new Color(params.color)
  CommonsMultipartFile file = request.getFile('color.filename')
  fileUploadService.upload(colorInstance, file, "foldername")
  if (requestInstance.save(flush: true)) {
    withFormat {
      html {redirect(action: "list") }
      js {render "test"}
    }
  }
}

我从这样的事情开始:...

I've started with something like this:...

import org.junit.Before
import grails.test.mixin.Mock
import grails.test.mixin.TestFor

@TestFor(ColorController)
@Mock(Color)
class ColorControllerTests {

    @Before
    void setUp() {
        controller.fileUploadService = new FileUploadService
    }
}

问题

  • 我不知道如何测试 CommonsMultipartFile 以进行文件上传.
  • 此外,此测试用例将位于 unit 测试文件夹中.我该如何执行?
  • I can't figure out how to test the CommonsMultipartFile for file upload.
  • Also, this test case will sit in unit test folder. How can I execute it?

推荐答案

由于在文件上传时请求将是multipart,因此实际请求的servlet 将是MultipartHttpServletRequest.对于单元测试用例,mockcontroller 中的request 一样使用.成功模拟后,您应该能够在测试中 addFileaction 中的 getFile.

Since the request will be multipart during file upload, the actual request servlet would be MultipartHttpServletRequest. For unit test case, mock the same and use it as the request in controller. On successful mocking you should be able to addFile in tests and getFile in action.

import org.junit.Before
import grails.test.mixin.Mock
import grails.test.mixin.TestFor

@TestFor(ColorController)
@Mock(Color)
class ColorControllerTests {

    @Before
    void setUp() {
        controller.fileUploadService = new FileUploadService
        //Mock MultipartHttpServletRequest somethign like below
        controller.metaClass.request = mockFor(MultipartHttpServletRequest).createMock()
    }

    void testFileUpload(){
         //Add a mock multipart file to request
         controller.request.addFile(new MockMultipartFile('myFile', 'IronMan3.jpg', 'image/jpeg', "1234567" as byte[]))

         //call the controller action
         //assert response
    }
}

这篇关于如何在 Grails 中测试文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆