Search code examples
c#socketsrhino-mocks

rhino mocks: how to build a fake socket?


I tried to build a fake socket for testing using the following code:

var socket = MockRepository.GenerateStub<Socket>(
    AddressFamily.InterNetwork, 
    SocketType.Stream, ProtocolType.IP
);
socket.Stub(v => v.RemoteEndPoint).PropertyBehavior().Return(
    new IPEndPoint(IPAddress.Parse("127.0.0.1"), 12345)
);

However, the attempt to create the stub for the read only-property gives me the following exception:

Invalid call, the last call has been used or no call has been made (make sure that you are calling a virtual (C#) / Overridable (VB) method).

Could anyone help me spot where it's going wrong?

Thanks


Solution

  • Thx Rup.

    I solved it in the way that I wrote a wrapper class for Socket that exposed all needed methods as virtual.

    public class SocketWrapper
    {
        private readonly Socket _socket;
    
        public SocketWrapper(Socket socket)
        {
            _socket = socket;
        }
    
        public virtual EndPoint RemoteEndPoint
        {
            get { return _socket.RemoteEndPoint; }
        }
    
        public virtual void Close()
        {
            _socket.Close();
        }
    
        public virtual void EndDisconnect(IAsyncResult asyncResult)
        {
            _socket.EndDisconnect(asyncResult);
        }
    
        public virtual bool Connected
        {
            get { return _socket.Connected; }
        }
    
        public virtual int Send(byte[] data)
        {
            return _socket.Send(data);
        }
    
        public virtual IAsyncResult BeginReceive(byte[] buffer, int offset, int size, SocketFlags flags, AsyncCallback callback, object state )
        {
            return _socket.BeginReceive(buffer, offset, size, flags, callback, state);
        }
    
        public virtual int EndReceive(IAsyncResult asyncResutl)
        {
            return _socket.EndReceive(asyncResutl);
        }
    
        public virtual IAsyncResult BeginDisconnect(bool reuseSocket,AsyncCallback callback, object state)
        {
            return _socket.BeginDisconnect(reuseSocket, callback, state);
        }
    }