问题
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
回答1:
where is my mistake?
The error message seems pretty self explanatory. You can only mock virtual methods. In your case you are trying to mock the getter of the RemoteEndPoint property but this property is not virtual => it is impossible to mock. Also it makes sense to create mocks for abstract class/interfaces. In your case you are trying to mock the Socket class which is impossible.
回答2:
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);
}
}
来源:https://stackoverflow.com/questions/8092182/rhino-mocks-how-to-build-a-fake-socket