Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking SFTP, FTP, FTPS, Local File System Server in Java

Tags:

java

sftp

ftp

I need to test FTP/FTPS/SFTP/Local File System protocols in Java.

I need a mock server which can be used in any of these methods.

I could find a MockFTPServer. According to my understanding, it can be used only for simple FTP protocol and not for FTPS/SFTP/Local File System.

Can anybody suggest if there is any mock implementation available for a server which supports FTP/FTPS/SFTP/Local File System in Java?

Thanks,

Vijay Bhore

like image 981
Here to Learn. Avatar asked Feb 26 '13 18:02

Here to Learn.


2 Answers

The questions is a bit older, but I post my answer anyway as it might help someone else as well.

I´ve written an article on how create a mock sftp server using Testcontainers and the atmoz/sftp Docker image, which is adaptable to your other requirements as well.

The full example can be seen here

You would define your TestContainer with SFTP like that

 private static final GenericContainer sftp = new GenericContainer(
            new ImageFromDockerfile()
                    .withDockerfileFromBuilder(builder ->
                            builder
                                    .from("atmoz/sftp:latest")
                                    .run("mkdir -p /home/" + USER + "/upload; chmod -R 007 /home/" + USER)
                                    .build()))
            //.withFileSystemBind(sftpHomeDirectory.getAbsolutePath(), "/home/" + USER + REMOTE_PATH, BindMode.READ_WRITE) //uncomment to mount host directory - not required / recommended
            .withExposedPorts(PORT)
            .withCommand(USER + ":" + PASSWORD + ":1001:::upload");

When you need an FTPS server or any other protocoll, you can pick another image like this for example and adapt the container configuration. https://hub.docker.com/r/bozorgiyan/ftps-server

As for the Local File System, I´m not sure if there is anything special required. With JUnit 5 you can easily create a temporary directory like so

@TempDir
File mockFileSystemDirectory;

And you can create a util class that rewrites your paths to that directory like so:

public static File convertToFakeFileSystem(File yourFile, File fakeFileSystem) {
    return new File(fakeFileSystem.getAbsolutePath() + yourFile
            .getAbsolutePath()
            .replaceAll("C://", "/"));
}
like image 172
Marian Klühspies Avatar answered Oct 16 '22 21:10

Marian Klühspies


There is Fake SFTP server rule. It is a rule/library for JUnit 4 that runs an SFTP server during test. It provides convenience method that help you to put files onto the server and get files from it.

Full Disclosure: I'm the author of Fake SFTP server rule.

like image 45
Stefan Birkner Avatar answered Oct 16 '22 20:10

Stefan Birkner