Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails java.io.File mocking

Tags:

grails

spock

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.

like image 708
Akolopez Avatar asked Apr 14 '14 04:04

Akolopez


People also ask

Can you use Mockito with Spock?

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/…

What is GroovySpy?

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)

How do you mock a method in Spock?

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.


1 Answers

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.

like image 193
Lari Hotari Avatar answered Sep 28 '22 07:09

Lari Hotari