我花了很长时间试图启动并运行一个可以测试我的 SFTP 服务的模拟框架。我熟悉 EasyMock、PowerMock 和 JMockit,但最终选择了 GMock。test ('org.gmock:gmock:0.8.2') { excludes 'junit' }
现在我已经成功运行了快乐路径测试,我正在编写我的重试逻辑,然后是我的失败场景。我现在遇到两个问题。我似乎无法找到解决方案,因为几乎所有 Grails 和 GMock 的文档都很少。
正在测试的方法:我正在使用这个博客的 SFTP 和 JCraft 的 JSch示例,并稍微扩展了它以满足我的需要。我接受用于连接的凭据和文件名。我创建了一个 FileOutputStream,然后连接到 SFTP 服务器。如果我遇到异常,那么我将重试第 n 次(出于 SO 目的在此处进行了简化)。
/**
* Transfers the file from the remote input server to the local output server.
*
* @param fileName
* - the file name
* @param inputFtpCredential
* - the input server
* @param outputFtpCredential
* - the output server
* @param mode
* - the mode for the transfer (defaults to {@link ChannelSftp#OVERWRITE}
* @throws SftpException if any IO exception occurs. Anything other than
* {@link ChannelSftp#SSH_FX_NO_SUCH_FILE SSH_FX_NO_SUCH_FILE} or {@link
* ChannelSftp#SSH_FX_PERMISSION_DENIED SSH_FX_PERMISSION_DENIED} may cause a retry
*/
public void transferRemoteToLocal(String fileName, FtpCredential inputFtpCredential, FtpCredential outputFtpCredential, Integer mode = ChannelSftp.OVERWRITE) {
for (retryCounter in 0 .. maxRetries) {
FileOutputStream output
try {
File file = new File(outputFtpCredential.remoteBaseDir, fileName);
// set stream to append if the mode is RESUME
output = new FileOutputStream(file, (mode == ChannelSftp.RESUME));
/*
* getting the file length of the existing file. This is only used
* if the mode is RESUME
*/
long fileLength = 0
if (file.exists())
fileLength = file.length()
load (output, fileName, inputFtpCredential, mode, fileLength)
// success
return
} catch (exception) {
// if an exception is thrown then retry a maximum number of times
if (retryCounter < maxRetries) {
// let the thread sleep so as to give time for possible self-resets
log.info "Retry number ${retryCounter+1} of file $fileName transfer after $sleepDuration ms"
Thread.sleep(sleepDuration)
mode = ChannelSftp.RESUME
} else {
int exceptionID = (exception instanceof SftpException)?(exception as SftpException).id:0
throw new SftpException(exceptionID, "Max number of file transfer retries ($maxRetries) exceeded on file $fileName", exception)
}
} finally {
if (output != null)
output.close()
}
}
}
def load(OutputStream outputStream, String fileName, FtpCredential ftpCredential, Integer mode, Long fileIndex = 0)
throws SocketException, IOException, SftpException, Exception {
connect(ftpCredential) { ChannelSftp sftp ->
sftp.get(fileName, outputStream, mode, fileIndex)
}
}
所以这与博客中的方法一起工作。我写了我的快乐路径场景并让它与 GMock 一起工作。
public void testSavingRemoteToLocal_Success() throws JSchException {
// Holders for testing
String fileToTransfer = 'test_large_file.txt'
FtpCredential localCredential = new FtpCredential()
// populate credential
FtpCredential remoteCredential = new FtpCredential()
// populate credential
// Mocks
File mockFile = mock(File, constructor(localCredential.remoteBaseDir, fileToTransfer))
mockFile.exists().returns(false)
FileOutputStream mockFOS = mock(FileOutputStream, constructor(mockFile, false))
// connection
JSch mockJSch = mock(JSch, constructor())
Session mockSession = mock(Session)
ChannelSftp mockChannel = mock(ChannelSftp)
mockJSch.getSession(remoteCredential.username, remoteCredential.server, remoteCredential.port).returns(mockSession)
mockSession.setConfig ("StrictHostKeyChecking", "no")
mockSession.password.set(remoteCredential.password)
mockSession.connect().once()
mockSession.openChannel("sftp").returns(mockChannel)
mockChannel.connect()
mockChannel.cd(remoteCredential.remoteBaseDir).once()
// transfer
mockChannel.get (fileToTransfer, mockFOS, ChannelSftp.OVERWRITE, 0)
// finally method mocks
mockChannel.exit()
mockSession.disconnect()
mockFOS.close()
// Test execution
play {
service.transferRemoteToLocal(fileToTransfer, remoteCredential, localCredential)
}
}
错误1:然后我做了一个简单的复制/粘贴,除了测试方法名称之外没有改变任何东西,我收到以下错误:
java.lang.StackOverflowError
at java.lang.ref.SoftReference.get(SoftReference.java:93)
at org.codehaus.groovy.util.ManagedReference.get(ManagedReference.java:41)
at org.codehaus.groovy.util.ManagedConcurrentMap$Entry.isEqual(ManagedConcurrentMap.java:62)
at org.codehaus.groovy.util.AbstractConcurrentMap$Segment.getOrPut(AbstractConcurrentMap.java:91)
at org.codehaus.groovy.util.AbstractConcurrentMap.getOrPut(AbstractConcurrentMap.java:35)
at org.codehaus.groovy.reflection.ClassInfo.getClassInfo(ClassInfo.java:103)
at org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl.getMetaClass(MetaClassRegistryImpl.java:227)
at org.codehaus.groovy.runtime.InvokerHelper.getMetaClass(InvokerHelper.java:751)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.createCallStaticSite(CallSiteArray.java:59)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.createCallSite(CallSiteArray.java:146)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)
at org.codehaus.groovy.runtime.callsite.StaticMetaClassSite.call(StaticMetaClassSite.java:55)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)
at org.codehaus.groovy.runtime.callsite.StaticMetaClassSite.call(StaticMetaClassSite.java:55)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)
at org.codehaus.groovy.runtime.callsite.StaticMetaClassSite.call(StaticMetaClassSite.java:55)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)
这会持续一段时间。
错误 2:然后我决定注释掉快乐路径并执行重试方案。所以我尝试在任何地方使用 .times(2) 并且它不喜欢构造函数上的 .times(2) 。如果我不这样做,那么它会抱怨,因为构造函数被调用了两次,因为重试会关闭所有内容,然后在重试时重新实例化它。
然后,我尝试创建两个直到失败的所有内容的模拟,并且在第二个 FileOutputStream 模拟的构建过程中引发了某种 NPE。它似乎正在对文件进行比较。
public void testSavingRemoteToLocal_RetryOnce() throws JSchException {
// Holders for testing
String fileToTransfer = 'test_large_file_desktop.txt'
FtpCredential localCredential = new FtpCredential()
// populate credential
FtpCredential remoteCredential = new FtpCredential()
// populate credential
// Mocks
// First loop that fails
File mockFile2 = mock(File, constructor(inputCredential.remoteBaseDir, fileToTransfer))
mockFile2.exists().returns(false)
FileOutputStream mockFIO2 = mock(FileOutputStream, constructor(mockFile2, false))
// connection
JSch mockJSch2 = mock(JSch, constructor())
Session mockSession2 = mock(Session)
mockJSch2.getSession(outputCredential.username, outputCredential.server, outputCredential.port).returns(mockSession2)
mockSession2.setConfig ("StrictHostKeyChecking", "no")
mockSession2.password.set(outputCredential.password)
mockSession2.connect().raises(new SftpException(0, "throw an exception to retry"))
mockSession2.disconnect()
mockFIO2.close()
// second loop that passes
File mockFile = mock(File, constructor(inputCredential.remoteBaseDir, fileToTransfer))
mockFile.exists().returns(false)
FileOutputStream mockFIO = mock(FileOutputStream, constructor(mockFile, true)) // <-- Fails here with a NPE in mockFile.compareTo
// connection
JSch mockJSch = mock(JSch, constructor())
Session mockSession = mock(Session)
ChannelSftp mockChannel = mock(ChannelSftp)
mockJSch.getSession(outputCredential.username, outputCredential.server, outputCredential.port).returns(mockSession)
mockSession.setConfig ("StrictHostKeyChecking", "no")
mockSession.password.set(outputCredential.password)
mockSession.connect()
mockSession.openChannel("sftp").returns(mockChannel)
mockChannel.connect()
mockChannel.cd(outputCredential.remoteBaseDir)
// transfer
mockChannel.get (fileToTransfer, mockFIO, FtpMonitor.getInstance(assetId), ChannelSftp.RESUME, 0)
// finally method mocks
mockChannel.exit()
mockSession.disconnect()
mockFIO.close()
// Test execution
play {
service.sleepDuration = 200
service.sftpCopyFrom(outputCredential, inputCredential, fileToTransfer, assetId )
}
// Assert the results
}