user1731553
user1731553

Reputation: 1937

How to force a port to be unavailable for testing purpose?

I have a function which tests if the given port is available or not:

public static boolean isPortAvailable(int port) throws IOException {
        boolean isAvailable = false;
        ServerSocket serverSocket = null;
        if (isValidPort(port)) {

            try {
                serverSocket = new ServerSocket(port);
                isAvailable = true;
            } catch (IOException ignore) {
                isAvailable = false;
            } finally {
                if (serverSocket != null) {
                    serverSocket.close();

                }
                serverSocket = null;
            }

        }
        return isAvailable;
    }

I need to test the false condition for this method using junit:

@Test
    public void testPortUnAvailable() throws IOException{
        int port = 49613 ;
        Assert.assertFalse(PortUtil.isPortAvailable(port));
    }

How should I force the port number 49613 or any other port to be unavailable for testing? Any other suggestion for better way to do the same is most welcome.

Upvotes: 0

Views: 613

Answers (1)

jarnbjo
jarnbjo

Reputation: 34313

Create a ServerSocket, which is bound to an arbitrary, free port. Using a hardcoded port like 49613 will make your test fail if the port is currently used by another application, over which you usually don't have much control. Test your method with the dynamically assigned port and then close the socket:

ServerSocket ss = new ServerSocket(0);
try {
    Assert.assertFalse(PortUtil.isPortAvailable(ss.getLocalPort()));
}
finally {
    ss.close();
}

It would also probably be better if your isPortAvailable method checks for java.net.BindException instead of any IOException, since other IOExceptions may mean that something else is wrong and not necessarily that the port is already in use.

Upvotes: 1

Related Questions