|
| 1 | +package com.baeldung.ftp; |
| 2 | + |
| 3 | +import org.junit.After; |
| 4 | +import org.junit.Before; |
| 5 | +import org.junit.Test; |
| 6 | +import org.mockftpserver.fake.FakeFtpServer; |
| 7 | +import org.mockftpserver.fake.UserAccount; |
| 8 | +import org.mockftpserver.fake.filesystem.DirectoryEntry; |
| 9 | +import org.mockftpserver.fake.filesystem.FileEntry; |
| 10 | +import org.mockftpserver.fake.filesystem.FileSystem; |
| 11 | +import org.mockftpserver.fake.filesystem.UnixFakeFileSystem; |
| 12 | + |
| 13 | +import java.io.File; |
| 14 | +import java.io.IOException; |
| 15 | +import java.net.URISyntaxException; |
| 16 | +import java.util.Collection; |
| 17 | + |
| 18 | +import static org.assertj.core.api.Assertions.assertThat; |
| 19 | + |
| 20 | +public class FtpClientIntegrationTest { |
| 21 | + |
| 22 | + private FakeFtpServer fakeFtpServer; |
| 23 | + |
| 24 | + private FtpClient ftpClient; |
| 25 | + |
| 26 | + @Before |
| 27 | + public void setup() throws IOException { |
| 28 | + fakeFtpServer = new FakeFtpServer(); |
| 29 | + fakeFtpServer.addUserAccount(new UserAccount("user", "password", "/data")); |
| 30 | + |
| 31 | + FileSystem fileSystem = new UnixFakeFileSystem(); |
| 32 | + fileSystem.add(new DirectoryEntry("/data")); |
| 33 | + fileSystem.add(new FileEntry("/data/foobar.txt", "abcdef 1234567890")); |
| 34 | + fakeFtpServer.setFileSystem(fileSystem); |
| 35 | + fakeFtpServer.setServerControlPort(0); |
| 36 | + |
| 37 | + fakeFtpServer.start(); |
| 38 | + |
| 39 | + ftpClient = new FtpClient("localhost", fakeFtpServer.getServerControlPort(), "user", "password"); |
| 40 | + ftpClient.open(); |
| 41 | + } |
| 42 | + |
| 43 | + @After |
| 44 | + public void teardown() throws IOException { |
| 45 | + ftpClient.close(); |
| 46 | + fakeFtpServer.stop(); |
| 47 | + } |
| 48 | + |
| 49 | + @Test |
| 50 | + public void givenRemoteFile_whenListingRemoteFiles_thenItIsContainedInList() throws IOException { |
| 51 | + Collection<String> files = ftpClient.listFiles(""); |
| 52 | + |
| 53 | + assertThat(files).contains("foobar.txt"); |
| 54 | + } |
| 55 | + |
| 56 | + @Test |
| 57 | + public void givenRemoteFile_whenDownloading_thenItIsOnTheLocalFilesystem() throws IOException { |
| 58 | + ftpClient.downloadFile("/foobar.txt", "downloaded_buz.txt"); |
| 59 | + |
| 60 | + assertThat(new File("downloaded_buz.txt")).exists(); |
| 61 | + new File("downloaded_buz.txt").delete(); // cleanup |
| 62 | + } |
| 63 | + |
| 64 | + @Test |
| 65 | + public void givenLocalFile_whenUploadingIt_thenItExistsOnRemoteLocation() throws URISyntaxException, IOException { |
| 66 | + File file = new File(getClass().getClassLoader().getResource("ftp/baz.txt").toURI()); |
| 67 | + |
| 68 | + ftpClient.putFileToPath(file, "/buz.txt"); |
| 69 | + |
| 70 | + assertThat(fakeFtpServer.getFileSystem().exists("/buz.txt")).isTrue(); |
| 71 | + } |
| 72 | + |
| 73 | +} |
0 commit comments