Reputation: 6717
i am writing a Class wich will be initialised with a Socket. I want to write a Test using an NUnit DynamicMock.
How can i create a Mock of the Socket without much effort?
DynamicMock DynamicSocketMock = new DynamicMock(typeof (Socket));
/*No ERROR - BUT I THINK HERE IS THE PROBLEM*/
Socket SocketMock = (Socket) DynamicSocketMock.MockInstance;
/*RUNTIME ERROR*/
ToBeTested Actual = new ToBeTested(SocketMock);
/*NEVER REACHED*/
Edit #1
I looked into moq nad it looks quite nice however i still can not test. My initial Problem was to find the rigth version to use, but i think i solved this.
var Mock = new Mock<Socket>();
Socket MockSocket = (Socket)Mock.Object;
ToBeTested Actual = new ToBeTested(SocketMock);
The Problem ist that Socket does not feature a Constructor without parameters. Now i do not want to give it a parameter, i want to mock everything.
Edit #2 This seems to be a problem for a lot of people The target is to create a mock directly from the socket.
Upvotes: 0
Views: 3298
Reputation: 6717
I resolved my issue.
The answer is DynamicMock just with Interfaces.
Moq just with prosperparameters or, since i want it easy a lot of times - here is what i did:
public class Test_MockSocket : Socket
{
public Test_MockSocket() : base (
(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 30000)).AddressFamily,
(SocketType.Stream),
(ProtocolType.Tcp))
{
}
}
And when setting up the test:
var Mock = new Mock<Test_MockSocket>();
Socket MockSocket = (Socket)Mock.Object;
ToBeTested Actual = new ToBeTested (MockSocket);
i can not think you can get it with less effort than this.
Upvotes: 0
Reputation: 12073
I think mocking Socket
is a fairly advanced task NUnit DynamicMock isn't suited for that, after all they don't pretend to be a real powerful mocking solution.
I am personally using Moq, and since Socket class isn't sealed I think mocking it with Moq should be pretty straightforward and suitable for your needs.
Nunit DynamicMock isn't very well documented and represented in internet it appears, but I took a look here into code from its constructor
looks like it isn't supposed to work with anything except interfaces, so you need to look into real mock framework once you need that.
Upvotes: 2