Search code examples
c#nunitmockingrhino-mocksnunit-mocks

Has anyone successfully mocked the Socket class in .NET?


I'm trying to mock out the System.net.Sockets.Socket class in C# - I tried using NUnit mocks but it can't mock concrete classes. I also tried using Rhino Mocks but it seemed to use a real version of the class because it threw a SocketException when Send(byte[]) was called. Has anyone successfully created and used a Socket mock using any mocking framework?


Solution

  • Whenever I run into these kinds of problems with Moq I end up creating an interface to abstract away the thing I can't mock.

    So in your instance you might have an ISocket interface that implements the Send method. Then have your mocking framework mock that instead.

    In your actual code, you'd have a class like this

    public class MySocket : ISocket
    {
      System.Net.Sockets.Socket _socket;
    
      public void MySocket(System.Net.Sockets.Socket theSocket)
      {
        _socket = theSocket;
      }
    
      public virtual void Send(byte[] stuffToSend)
      {
        _socket.Send(stuffToSend);
      }
    
    }
    

    Not sure if that meets your needs, but it's an option.