gpt4 book ai didi

spock - 我如何使用 Spock spy ?

转载 作者:行者123 更新时间:2023-12-05 06:27:38 25 4
gpt4 key购买 nike

我尝试使用 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)

表示真正的方法被调用了。有什么原因它不起作用吗?

最佳答案

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

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

关于spock - 我如何使用 Spock spy ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55097304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com