Using Apache Mina as a Mock/In Memory SFTP Server for Unit Testing

前端 未结 1 530
有刺的猬
有刺的猬 2021-01-01 19:32

I am having a bit of trouble working out how to use Apache Mina. Their documentation is a bit scant for my talentless brain to work out. I have seen the helpful starting cod

相关标签:
1条回答
  • 2021-01-01 19:49

    Here is what I did (JUnit):

      @Test
      public void testPutAndGetFile() throws JSchException, SftpException, IOException
      {
        JSch jsch = new JSch();
    
        Hashtable<String, String> config = new Hashtable<String, String>();
        config.put("StrictHostKeyChecking", "no");
        JSch.setConfig(config);
    
        Session session = jsch.getSession( "remote-username", "localhost", PORT);
        session.setPassword("remote-password");
    
        session.connect();
    
        Channel channel = session.openChannel( "sftp" );
        channel.connect();
    
        ChannelSftp sftpChannel = (ChannelSftp) channel;
    
        final String testFileContents = "some file contents";
    
        String uploadedFileName = "uploadFile";
        sftpChannel.put(new ByteArrayInputStream(testFileContents.getBytes()), uploadedFileName);
    
        String downloadedFileName = "downLoadFile";
        sftpChannel.get(uploadedFileName, downloadedFileName);
    
        File downloadedFile = new File(downloadedFileName);
        Assert.assertTrue(downloadedFile.exists());
    
        String fileData = getFileContents(downloadedFile);
    
        Assert.assertEquals(testFileContents, fileData);
    
        if (sftpChannel.isConnected()) {
          sftpChannel.exit();
          System.out.println("Disconnected channel");
        }
    
        if (session.isConnected()) {
          session.disconnect();  
          System.out.println("Disconnected session");
        }
    
      }
    
      private String getFileContents(File downloadedFile)
        throws FileNotFoundException, IOException
      {
        StringBuffer fileData = new StringBuffer();
        BufferedReader reader = new BufferedReader(new FileReader(downloadedFile));
    
        try {
          char[] buf = new char[1024];
          for(int numRead = 0; (numRead = reader.read(buf)) != -1; buf = new char[1024]) {
            fileData.append(String.valueOf(buf, 0, numRead));
          }
        } finally {    
          reader.close();
        }
    
        return fileData.toString();
      }
    
    0 讨论(0)
提交回复
热议问题