My server code looks something like this:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server implements Runnable {
private ServerSocket serverSocket;
public Server(int port) throws IOException {
serverSocket = new ServerSocket(port);
}
@Override
public void run() {
try {
Socket client = serverSocket.accept();
// do stuff
} catch (IOException e) {
e.printStackTrace();
}
}
}
My plan was to write a mock client that connects to the server socket, and verifies the result, but in order to do that I need to know which port to connect to. However, this information is private.
None of the options I was thinking about are good practice I think:
- If I use a predefined port number for the tests, I have no guarantee that it will be available. Even if it's available just before the test, it might be, theoretically snatched by the time I try to use it.
- If I pass 0 as port number (so that
ServerSocket
will atomically provide a free port), I still have no access to it. - I could add a
getServerPort()
method to the interface or create a constructor that accepts aServerSocket
object, but changing the interface only for the sake of testing is considered bad practice.