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.
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.
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.
useObjenesis: true
. According to the website, Objenesis enables creating objects without passing constructor parameters. (Note that all the constructors for File require parameters) –
Kp © 2022 - 2024 — McMap. All rights reserved.