Grails: Mock Testing a File Upload

Here is a quick note on how to mock test a file upload feature in a Grails application (credits: Luke Daley). A little trick is needed here because by default in the unit tests, Grails will only give you an instance of MockHttpServletRequest as the request and that does not have any support for multipart/form-data.

But, hey, you are using the ultra-dynamic Groovy language underneath. How difficult could it be to turn Grails’ arm a bit to make it give you a multipart http request instead (MockMultipartHttpServletRequest)!

Here is how you can do it:

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
        ....
    }
}
Advertisements