我的程序打开 sftp 连接并连接到服务器以获取然后处理的文件。 我正在为此方法编写一个测试用例,试图模拟连接。
我的实际课程是:
public void getFile() {
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
String path = ftpurl;
try {
JSch jsch = new JSch();
session = jsch.getSession(username, host, port);
session.setConfig("StrictHostKeyChecking", "no");session.setPassword(JaspytPasswordEncryptor.getDecryptedString(jaspytEncryptionKey, jaspytEncryptionAlgorithm, password));
session.connect();
channel = session.openChannel("sftp");
channel.connect();
channelSftp = (ChannelSftp) channel;
channelSftp.cd(path);
Vector<ChannelSftp.LsEntry> list = channelSftp.ls("*.csv");
for (ChannelSftp.LsEntry entry : list) {
if (entry.getFilename().startsWith("A...")) {
findByFileName(entry.getFilename());
}
}
channelSftp.exit();
session.disconnect();
} catch (JSchException e) {
LOGGER.error("JSch exception"+e);
} catch (SftpException e) {
LOGGER.error("Sftp Exception"+e);
}
}
目前测试课程:
@Test
public void getNamesTestValid() throws IOException, JSchException {
JSch jsch = new JSch();
Hashtable config = new Hashtable();
config.put("StrictHostKeyChecking", "no");
JSch.setConfig(config);
Session session = jsch.getSession( "remote-username", "localhost", 22999);
session.setPassword("remote-password");
session.connect();
Channel channel = session.openChannel( "sftp" );
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
Mockito.when(fileRepository.findByFileName(fileName)).thenReturn(fileDetail);
scheduler.getCSVFileNames();
}
当尝试模拟连接时,它会搜索实际端口,错误是端口无效,连接被拒绝。 我只想嘲笑这种联系。 我的另一个疑问是在模拟连接之后我应该从哪里读取文件详细信息。
那是因为您正在与
new Jsch()
创建实际连接。您需要模拟与 Mockito
等库的连接。例如:
@RunWith(MockitoJUnitRunner.class)
class Test {
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private JSch mockJsch;
..
void test() {
Session mockSession = mockJsch.getSession("username", "localhost", 22999);
..
}
}