Search code examples
groovyspock

test void simple method with spock


I have the following method need to be tested:

class Person {

    String getFileName(String number) {
         return "file"+number
    }

    void updateSpec(String number) {
         new File(getFileName(number)).delete()
    }
}

I try to create the testcase like this:

def "update spec"() {
        given:
            Person person = new Person()

        when:
            person.updateSpec('1')

        then:
            1 * File.delete()
    }

it says:

Too few invocations for:

1 * File.delete()   (0 invocations)

what is the problem and how to fix it, thanks!

And is there a good way to test this method?


Solution

  • Depends on what do you want to test. At first you have to use Mock or Spy to be able to test invocation count.

    For example you can test if getFileName() method was called from updateSpec() method and if it was called with '1' argument like this:

    def "update spec"() {
        given:
        Person person = Spy(Person)
    
        when:
        person.updateSpec('1')
    
        then:
        1 * person.getFileName('1')
    }
    

    If you really need to test whether the File.delete() was called, then it will be better to change Person class little bit, because you need File mock on which you can check the invocation count:

    class Person {
        File getFile(String number) {
            return new File("file" + number)
        }
    
        void updateSpec(String number) {
            getFile(number).delete()
        }
    }
    

    And the test can be then:

    def "File delete was called"() {
        given:
        File file = Mock(File)
        Person person = Spy(Person)
        person.getFile(_) >> file
    
        when:
        person.updateSpec('1')
    
        then:
        1 * file.delete()
    }
    

    Another option will be to inject some FileService, wich will encapsulate the File.delete() method, into the Person class and test invoication on it.