10

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.

Akolopez
  • 334
  • 1
  • 4
  • 14

1 Answers1

10

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.

Lari Hotari
  • 5,190
  • 1
  • 36
  • 43
  • I didn't know you could use Mock on jdk api. Not really what I was looking for, but it helped. Thanks! – Akolopez Apr 14 '14 at 05:28
  • 1
    You'd either use a mock *or* a global spy, depending on whether you want to mock a specific or all instances. – Peter Niederwieser Apr 14 '14 at 06:13
  • 2
    For those who share my curiosity (and ignorance) regarding `useObjenesis: true`. According to the website, [Objenesis](http://objenesis.org/) enables creating objects without passing constructor parameters. (Note that all the constructors for [File](https://docs.oracle.com/javase/7/docs/api/java/io/File.html) require parameters) – Ryan Heathcote Feb 06 '16 at 01:50
  • @RyanHeathcote Really appreciate putting that info down, I wouldn't have found this info myself via Google if not for your comment. – haridsv Nov 21 '22 at 14:43