Rhino mocks: how to create a fake socket?

I tried to create 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, trying to create a stub for the read only-only property gives me the following exception:

Invalid call, last call used or no call made (make sure you call the virtual (C #) / Overridable (VB) method).

Can someone help me determine where this is happening?

thanks

+4
source share
2 answers

thanks Rup.

I solved it the way I wrote the shell class for Socket, which revealed all the necessary 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); } } 
+2
source

Where is my mistake?

The error message seems pretty straightforward. You can only simulate virtual methods. In your case, you are trying to mock the recipient of the RemoteEndPoint property, but this property is not virtual => cannot be ridiculed. It also makes sense to create mocks for an abstract class / interfaces. In your case, you are trying to make fun of the Socket class, which is not possible.

+2
source

Source: https://habr.com/ru/post/1380735/


All Articles