I have a such method:
public boolean isFree(LdapPort port) {
boolean result = false;
try{
ServerSocket ss = new ServerSocket(port.getPortNumber());
ss.getLocalPort();
ss.close();
} catch(IOException ex){
result = true;
}
return result;
}
The problem is, that getLocalPort()
operates on real system ports and during testing it passes depending on the local system.
What should be the valid way to test such method?
The ServerSocket
instance should be available via factory, which (factory) is passed as a dependency to your class:
// Passing factory dependency via constructor injection
public PortChecker(IServerSocketFactory socketFactory)
{
this.socketFactory = socketFactory;
}
// ...
ServerSocket ss = this.socketFactory.GetServerSocket(port.getPortNumber());
ss.getLocalPort();
ss.close();
Then, in your unit test you can mock socketFactory
to return fake server socket and as a result "disconnect" it from any real world systems.
Note that ServerSocket
might also need to be abstraction (say, represented by interface/base class) so it can be mocked too.