我正在使用apache commons VFS
连接到 sftp 服务器并将文件内容写入 /input
目录到 /output
中的单个文件输入目录中的文件名称以 List
的形式提供。 。我正在努力写Junit
它的测试用例。我的意图是,一旦代码被执行,我将比较 /input
中的文件内容针对 /output
中的文件内容
public void exportFile(List<String> fileNamesList){
for (String file : fileNamesList){
try(FileObject fileObject= //getsFileObject
OutputStream fileOutputStream= fileObject.resolveFile("/output/"+"exportfile.txt").getContent().getOutputStream(true);
)
fileObject.resolveFile("/input/"+file).getContent().getInputStream().transferTo(fileOutputStream);
}
}
我想为上面的内容编写Junit测试用例。以下是我的测试用例设置
@BeforeAll
static void setUpSftpServer() throws IOException {
System.out.println("inside setup ssh");
sshd= SshServer.setUpDefaultServer();
sshd.setPort(1234);
sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider());
sshd.setPublickeyAuthenticator(AcceptAllPublickeyAuthenticator.INSTANCE);
sshd.setSubsystemFactories(Arrays.asList(new SftpSubsystemFactory()));
sshd.start();
}
@Test
void exportFileTest() throws IOException, URISyntaxException {
System.out.println("Inside exportFile test");
FileObject fileObject=getFileObject();
when(sftpConfiguration.connect()).thenReturn(fileObject);
myobject.exportFile(Arrays.asList("a.txt"));
String actualContent=fileObject.resolveFile("/input/a.txt").getContentContent().getString("UTF-8");
String expectedContent=fileObject.resolveFile("/output/exportFile.txt").getContentContent().getString("UTF-8");
assertTrue(actualContent.equals(expectedContent));
}
static FileObject getFileObject() throws URISyntaxException, FileSystemException {
String userInfo = "uname" + ":" + "pwd";
SftpFileSystemConfigBuilder sftpConfigBuilder = SftpFileSystemConfigBuilder.getInstance();
FileSystemOptions options = new FileSystemOptions();
IdentityProvider identityInfo = new IdentityInfo(new File("/fake/path/to/key"), "test".getBytes());
sftpConfigBuilder.setIdentityProvider(options, identityInfo);
URI uri= new URI("sftp", userInfo, "127.0.0.1", Objects.requireNonNullElse(1234, -1), null, null, null);
FileObject fileObject= VFS.getManager().resolveFile(uri.toString(),options);
System.out.println("creating file object complete");
fileObject.resolveFile("/input").createFolder(); //create a folder in the path
fileObject.resolveFile("/output").createFolder();
//code to create a file called a.txt inside /input and write the string "abc" to the file
return fileObject;
}
但是我遇到了如下异常
org.apache.commons.vfs2.FileSystemException: Unknown message with code "Could not get the user id of the current user (error code: -1)".
我在线路上遇到这个异常
FileObject fileObject= VFS.getManager().resolveFile(uri.toString(),options);
如何正确编写此案例的单元测试?
最佳答案
这是由于 SftpFileSystem
无法运行命令 id -u
造成的,该命令在某些 SSH 连接(例如 Windows OpenSSH)上不存在。它在尝试检测执行 channel 时运行此命令。通过添加以下 SFTP 配置来解决此问题:
sftpConfigBuilder.setDisableDetectExecChannel(options, true);
参见here .
关于java - 编写用于在 sftp 服务器中合并文件的 Junit 测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74034083/