Question

Is there any way to mock a file for unit testing in Grails?

I need to test file size and file type and it would help if I could mock these.

Any link to a resource would help.

Was it helpful?

Solution

You can mock java.io.File in Groovy code with Spock.

Here's an example of how to do it:

import spock.lang.Specification

class FileSpySpec extends Specification {
    def 'file spy example' () {
        given:
        def mockFile = Mock(File)
        GroovySpy(File, global: true, useObjenesis: true)
        when:
        def file = new File('testdir', 'testfile')
        file.delete()
        then :
        1 * new File('testdir','testfile') >> { mockFile }
        1 * mockFile.delete()
    }
}

The idea is to return the file's Spock mock from a java.io.File constructor call expectation which has the expected parameters.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top