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.
We can use Mockito stubbing, not Spock's. It works well! To help you with spock mocks, Spock also has annotations to setup mocks from the Subject Collaborator extension: github.com/marcingrzejszczak/…
GroovySpy(Closure interactions) Creates a Groovy spy with the specified interactions whose type and name are inferred from the left-hand side of the enclosing assignment. Object. GroovySpy(Map<String,Object> options)
In Spock, a Mock may behave the same as a Stub. So we can say to mocked objects that, for a given method call, it should return the given data. So generally, this line says: itemProvider. getItems will be called once with ['item-'id'] argument and return given array.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With