Has anyone successfully mocked the Socket class in .NET?

后端 未结 5 1064
深忆病人
深忆病人 2021-01-02 08:38

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 see

5条回答
  •  醉酒成梦
    2021-01-02 09:04

    The above class only Mocks your Send Method. This actually mocks a Socket. It Inherits all of Socket and then Implements the ISocket interface. ISocket needs to implement the signatures of any Socket methods or properties you need to mock

    //internal because only used for test code
    internal class SocketWrapper : Socket, ISocket
    {
        /// 
        /// Web Socket
        /// 
        public SocketWrapper():base(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
        {
        }
    
        //use all features of base Socket
    }
    

    The interface looks like this with two methods declined:

    public interface ISocket
    {
        void Connect(IPAddress address, int port);
        int Send(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode);
    }
    

    The Class that uses them has 2 constructors. One injects an ISocket for testing and then one that makes it's own Socket that the application uses.

    public class HTTPRequestFactory3
    {
    internal ISocket _socket;
    
    
        /// 
        /// Creates a socket and sends/receives information.  Used for mocking to inject ISocket
        /// 
        internal HTTPRequestFactory3(ISocket TheSocket)
        {
         _socket = TheSocket as ISocket;
         this.Setup();
        }
    
        /// 
        /// Self Injects a new Socket.
        /// 
        public  HTTPRequestFactory3()
        {
            SocketWrapper theSocket = new SocketWrapper();
            _socket = theSocket as ISocket;
            this.Setup();
        }
    }
    

    Then your tests can create a ISocket, set up expectations and verify them running all the same code the above class will use with a real socket. This test validates that section code.

       [Test]
       public void NewSocketFactoryCreatesSocketDefaultConstructor()
            {
                webRequestFactory = new HTTPRequestFactory3();
                Assert.NotNull(webRequestFactory._socket);
                Socket testSocket = webRequestFactory._socket as Socket;
                Assert.IsInstanceOf(testSocket);
            }
    

提交回复
热议问题