lundi 15 août 2016

How to test method that internally creates and uses a ServerSocket

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();
        }
    }
}

I want to use junit to unit test the server. I need to know which port to connect to in the test, but this information is private.

None of the options I was thinking about are good practice I think:

  1. 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.
  2. If I pass 0 as port number (so that ServerSocket will atomically provide a free port), I still have no access to it.
  3. I could add a getServerPort() method to the interface or create a constructor that accepts a ServerSocket object, but changing the interface only for the sake of testing is considered bad practice.

Aucun commentaire:

Enregistrer un commentaire