如何使用Spock Spy?

时间:2019-03-11 07:50:12

标签: spock spy

我尝试使用间谍测试,但没有成功。下面的类是Sut。

public class FileManager {
    public int removeFiles(String directory)    {
        int count = 0;
        if(isDirectory(directory))  {
            String[] files = findFiles(directory);
            for(String file : files)    {
                deleteFile(file);
                count++;
            }
        }
        return count;
    }

    private boolean isDirectory(String directory) {
        return directory.endsWith("/");
    }

    private String[] findFiles(String directory) {
        // read files from disk.
        return null;
    }

    private void deleteFile(String file)    {
        // delete a file.
        return;
    }
}

然后,我创建了如下所示的测试。

class SpyTest extends Specification  {
def "Should return the number of files deleted"()   {
    given:
    def fileManager = Spy(FileManager)
    1 * fileManager.findFiles("directory/") >> { return ["file1", "file2", "file3", "file4"] }
    fileManager.deleteFile(_) >> { println "deleted file."}

    when:
    def count = fileManager.removeFiles("directory/")

    then:
    count == 4
}

但是我得到了NullPointerException。

java.lang.NullPointerException
at example.spock.mock.FileManager.removeFiles(FileManager.java:8)
at net.sf.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.spockframework.mock.runtime.CglibRealMethodInvoker.respond(CglibRealMethodInvoker.java:32)
at org.spockframework.mock.runtime.MockInvocation.callRealMethod(MockInvocation.java:60)
at org.spockframework.mock.CallRealMethodResponse.respond(CallRealMethodResponse.java:29)
at org.spockframework.mock.runtime.MockController.handle(MockController.java:49)
at org.spockframework.mock.runtime.JavaMockInterceptor.intercept(JavaMockInterceptor.java:72)
at org.spockframework.mock.runtime.CglibMockInterceptorAdapter.intercept(CglibMockInterceptorAdapter.java:30)
at example.spock.mock.SpyTest.Should return the number of files deleted(SpyTest.groovy:13)

这意味着调用了真正的方法。有什么原因不起作用?

1 个答案:

答案 0 :(得分:0)

在Spock中,您不能模拟Java类的私有方法。查看您的FileManager尚不清楚为什么只有removeFiles是公开的而其他人是私有的。虽然所有方法都与文件管理有关。可能的解决方案是:

  1. 将其余FileManager个方法公开。这样,Spock可以工作,FileManager实际上将成为文件管理器,而不仅仅是文件删除器
  2. FileManager分解为不同的组件。因此,您可以分别模拟这些组件,并将它们注入“文件删除器”中。基本上,您已经在方法级别分解了代码。但是私有java方法是not mockable in Spock。而且类分解可能会产生开销,因为FileManager与其所有操作都具有内聚性
  3. 使用其他可以模拟私有方法的测试/模拟框架。例如。 Mockito和Powermock。但是,嘲笑私有方法是最糟糕的选择,因为如果失控,从长远来看,这可能会损害整个代码库的可维护性
相关问题