1

In my project I have a class that checks all ports at localhost and returns true if port is free and false if it is not. The solution is based on this answer

I need somehow to test it. Is there a way to temporarily use the port and then to free it back?

I've tried to use TcpListener Start with no success. If I use TcpClient Connect I get System.Net.Sockets.SocketException No connection could be made because the target machine actively refused it 127.0.0.1:myPort.

Here's the code I use:

class TestPortLocker
{
    public TcpClient client;
    public TcpListener listener;

    public void Lock(int port)
    {
        client = new TcpClient();
        client.Connect("localhost", port);
        //listener = new TcpListener(port);
        //listener.Start();
    }

    public void Stop()
    {
        client.Close();
        //listener.Stop();
    }
}
Community
  • 1
  • 1
kravasb
  • 696
  • 5
  • 16

1 Answers1

1

You can write a unit test to examine your code. Here's a little pseudo-code for your unit test method and supposed method under test.

Suppose you have a method for this class that you want to test:

public class PortManager 
{
    private _portChecker = portChecker;
    public PortManager(IPortChecker portChecker)
    {
       _portChecker = portChecker;
    }

    public bool PortsAreFree(int start, int end)
    {
        for(int i = start, i <= end; i++)
            if(!_portChecker.IsPortOpen(i))
                 return false;
        return true;
    }
}

Now to test this method you can use a mock for IPortChecker:

[TestFixture]
public class PortManagerTests
{
    [Test]
    public void PortsAreFree_APortIsLocked_ReturnsFalse()
    {
          var mock = new Mock<IPortChecker>();
          mock.Setup(x=> x.IsPortOpen(77)).Returns(false);

          var portManager = new PortManager(mock.Object);

          Assert.Equal(true, portManager.PortsAreFree(1, 76));
          Assert.Equal(true, portManager.PortsAreFree(78, 200));
          Assert.Equal(false, portManager.PortsAreFree(1, 200));
    }
}

}

brz
  • 5,926
  • 1
  • 18
  • 18