moq mocking a buffer[] argument
I am trieing to mock the receive method of a socket.
Here is workaround that i use to get the mock to work.
public class Test_MockSocket : Socket
{
public Test_MockSocket() : base (
(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 30000)).AddressFamily,
(SocketType.Stream),
(ProtocolType.Tcp))
{
}
}
and this is the current version of the test:
[Test]
public void ShouldReadFromSocket()
{
byte[] thingy = null;
var Mock = new Mock<Test_MockSocket>();
Mock.Setup(foo => foo.Receive(It.IsAny<byte[]>())).Returns(1);
Socket MockSocket = (Socket)Mock.Object;
Assert.AreEqual(1, MockSocket.Receive(thingy));
}
i want to mock a receive process with this, however i fail just trying this simple response. The failure is "System.NotSupportedException : Invalid setup on a non-virtual (overridable in VB) member: foo => foo.Receive(It.IsAny())"
why is my setup wrong an开发者_运维问答d what do i need to change to return a textstring as the byte[] buffer parameter.
You can only mock virtual methods and properties on a class. You can mock any member on an interface. The Receive
method on the Socket
class is not declared virtual, so Moq can't inject behavior in the code.
Because the .NET framework classes are usually not ideal for mocking, my understanding (which, admittedly, is limited), is that you want to create an abstraction layer for your communication. So instead of dealing directly with the socket, you would deal with your own set of interfaces and classes that hide all of the complexity of your communication. Not only does it make is easier to mock, it makes your communication easily interchangeable with other technologies, since your classes are loosely coupled.
Interfaces are far easier to moq than classes, that is, unless your class is an abstract class, or a base class with default implementations and virtual members for extension.
精彩评论