我对 Spock Mock() 对象有疑问。我有一个我正在尝试测试的 java 类。这个类做了一些我想模拟的 ftp 东西。我的示例代码
class ReceiveDataTest extends Specification{
String downloadPath = 'downloadPath';
String downloadRegex = 'downloadRegex';
SftpUtils sftpUtils = Mock();
ReceiveData receiveData;
def setup(){
sftpUtils.getFileNames(downloadPath,downloadRegex) >> ['file1', 'file2']
receiveData= new ReceiveData()
receiveData.setDownloadPath(downloadPath)
receiveData.setDownloadRegex(downloadRegex)
receiveData.setSftpUtils(sftpUtils);
}
def "test execute"() {
given:
def files = sftpUtils.getFileNames(downloadPath,downloadRegex)
files.each{println it}
when:
receiveData.execute();
then:
1*sftpUtils.getFileNames(downloadPath,downloadRegex)
}
}
public class ReceiveData(){
//fields, setters etc
public void execute() {
List<String> fileNames = sftpUtils.getFileNames(downloadPath, downloadRegex);
for (String name : fileNames) {
//dowload and process logic
}
}
}
现在,在“测试执行”中,files.each{} 打印出预期的内容。但是,当调用 receiveData.execute() 时,我的 sftpUtils 返回 null .. 有什么想法吗?
编辑也许我没有很好地说明我的问题 - 我不想只检查是否调用了 getFileNames。我需要结果来正确检查 for 循环。如果我在执行中注释循环,则测试通过。但由于我使用 getFilenames() 方法的结果,我得到一个 NPE 执行方法到达 for 循环。用 mockito 我会做这样的事情
Mockito.when(sftpUtils.getFilenames(downloadPath, downloadRegex)).thenReturn(filenamesList);
receiveData.execute();
Mockito.verify(sftpUtils).getFilenames(downloadPath, downloadRegex);
//this is what I want to test and resides inside for loop
Mockito.verify(sftpUtils).download(downloadPath, filenamesList.get(0));
Mockito.verify(sftpUtils).delete(downloadPath, filenamesList.get(0));
但我不能在 Spock 中使用 Mockito.verify() 然后阻塞