Static spock-mock method not working

I am trying to mock a static method readAttributesusing the groovy convention metaClass, but the real get method is being called.

This is how I made fun of the static function:

def "test"() {
    File file = fold.newFile('file.txt')
    Files.metaClass.static.readAttributes = { path, cls ->
        null
    }

    when:
        fileUtil.fileCreationTime(file)
    then:
        1 * fileUtil.LOG.debug('null attribute')
}

Am I doing something wrong here?

My java method

public Object fileCreationTime(File file) {
    try {
        BasicFileAttributes attributes = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
        if(attributes == null) {
            LOG.debug("null attribute");
        }  
        //doSomething
    } catch (IOException exception) {
        //doSomething
    }
    return new Object();
}
+4
source share
2 answers

The short answer is that this is not possible, look at this question.

It would be possible if:

  • The test code was written in groovy
  • The mocked (modified) class must be created in groovy code.

, , , , Files.

+3

, . test class, .

public BasicFileAttributes readAttrs(File file) throws IOException {
    return Files.readAttributes(file.toPath(), BasicFileAttributes.class);
}

.

FileUtil util = Spy(FileUtil);
util.readAttrs(file) >> { null }

.

+3

All Articles