Search code examples
spring-bootftptestcontainers

TestContainers FTP test fails


I have a simple test

   @TestInstance(TestInstance.Lifecycle.PER_CLASS)
    class PurchaseFZ223FtpServiceTest {
    
        private static final int PORT = 21;
        private static final String USER = "";
        private static final String PASSWORD = "";
        private static final int PASSIVE_MODE_PORT =21000;
    
        @Container
          FixedHostPortGenericContainer<?> ftp = new FixedHostPortGenericContainer<>(
                "delfer/alpine-ftp-server:latest")
                .withFixedExposedPort(PASSIVE_MODE_PORT, PASSIVE_MODE_PORT)
                .withExposedPorts(PORT)
                .withEnv("USERS", USER + "|" + PASSWORD)
                .withEnv("MIN_PORT", String.valueOf(PASSIVE_MODE_PORT))
                .withEnv("MAX_PORT", String.valueOf(PASSIVE_MODE_PORT));
    
        private final FTPClient client = new FTPClient();
    
        @BeforeAll
        void init() throws NoSuchFieldException, IllegalAccessException, IOException {
            ftp.start();
            client.connect("localhost", ftp.getMappedPort(PORT));
//some test logic 

and everything works good when i start test on local pc, and when i tried to build this with gitlab it start test and it always fails on client.connect("localhost", ftp.getMappedPort(PORT));

with exception: connection refused

do someone know what i missed or what is going wrong

ps. i checked for ftp is created and is running - and yes its running and its created, also i checked for ftp.getMappetPort(Port) and it will return something like this 53123

do not understand what do i miss


Solution

  • You are using FixedHostPortGenericContainer, which is deprecated and which does not work in all environments. Especially CIs can be a problem, since the port might already be in use. Furthermore, on your CI, the container might not be reachable on localhost, which you use as a hardcoded value in client.connect().

    Also, when you use FixedHostPortGenericContainer, you should not use getMappedPort(), but can use the hardcoded port directly.

    In order to make your configuration more robust, change to using GenericContainer together with withExposedPort(), getHost() (it might be the container is not reachable on localhost) and getMappedPort().