Grails java.io.File mocking
Asked Answered
K

1

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.

Keelykeen answered 14/4, 2014 at 4:14 Comment(0)
I
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.

Infract answered 14/4, 2014 at 5:23 Comment(4)
I didn't know you could use Mock on jdk api. Not really what I was looking for, but it helped. Thanks!Keelykeen
You'd either use a mock or a global spy, depending on whether you want to mock a specific or all instances.Womanize
For those who share my curiosity (and ignorance) regarding useObjenesis: true. According to the website, Objenesis enables creating objects without passing constructor parameters. (Note that all the constructors for File require parameters)Kp
@RyanHeathcote Really appreciate putting that info down, I wouldn't have found this info myself via Google if not for your comment.Amalgam

© 2022 - 2024 — McMap. All rights reserved.