1

How can I spy for the Class File in anthoer function in class?
Works for the test when I use new File in the test but not in my class.

public class Clazz {
    public void fun(String path) {
        File file = new File(path);
        if (!file.exists()) {
            throw new FileNotFoundException();
        }
    }
}


//Spock-test
class test extends Specification {
    given:
    GroovySpy(File, global: true, useObjenesis: true)
    def mockFile = Mock(File) {
      exists() >> true
    }
    new File(path) >> {mockFile}

    when:
    Clazz.fun("test.file")

    then:
    ...
    ...
}
Kfir
  • 11
  • 2
  • Wouldn't be easier if you pass `File file` instead of `String path`? If you use `File` to get content of some file you could even generalize to `InputStream` so you can use `FileInputStream` as well as other input stream types. – Szymon Stepniak Jan 23 '18 at 14:29
  • Thanks for the answer. I already thought about that, but it's makes me another problem with something else. Is it even possible to do what I want? – Kfir Jan 23 '18 at 14:37
  • 1
    I use spock for years and I have never mock global class, because it smells with bad design decisions. I would strongly suggest rethinking your class design and simplify it. – Szymon Stepniak Jan 23 '18 at 14:45

1 Answers1

0

From official spock docs about Spy:

Think twice before using this feature. It might be better to change the design of the code under specification.

http://spockframework.org/spock/docs/1.0/interaction_based_testing.html

And there are no reason to use spy object in test like that. If you don't like to redesign code, you can always use groovy metaprogramming:

File.metaClass.exists = {true}
Evgeny Smirnov
  • 2,886
  • 1
  • 12
  • 22
  • Thanks. The problem is that overwrite the method only in spock-test and not in the Java class – Kfir Jan 24 '18 at 08:56
  • yeah. It works in groovy code. But why do you need to use it in your classes? – Evgeny Smirnov Jan 24 '18 at 11:52
  • When I write unit test, there is no right path and then I get throw because the file not exists. The rest of the method not continue. – Kfir Jan 24 '18 at 16:31