Using Moles to mock System.Net.Sockets
-
28-10-2019 - |
Frage
I'm trying to use Moles to mock the Socket class in System.Net.Sockets. I have successfully generated the .moles file and building it did add a System.Net.Moles assembly to my references but It dose not generate the MSocket class. In fact only the MIPEndPointCollection class is generated.
Here is a sample class that uses System.Net.Sockets.Socket:
using System.Text;
using System.Net.Sockets;
namespace MyProject
{
public static class Communicator
{
public static int Send(string messages)
{
byte[] bytes = Encoding.ASCII.GetBytes(messages);
int bytesSent = 0;
using (Socket socket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp))
{
socket.Connect("localhost", 1234);
bytesSent = socket.Send(bytes);
}
return bytesSent;
}
}
}
A dumy test class:
using MyProject;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Net.Moles;
using Microsoft.Moles.Framework;
[assembly: MoledType(typeof(System.Net.Sockets.Socket))]
namespace MyProjectTest
{
[TestClass()]
public class CommunicatorTest
{
private TestContext testContextInstance;
public TestContext TestContext
{
get { return testContextInstance; }
set { testContextInstance = value; }
}
[TestMethod()]
[HostType("Moles")]
public void SendTest()
{
//dose not exist in the System.Net.Moles namespace:
//MSocket.Send = deligate(){ return 0; };
int bytesSent = Communicator.Send("Test Message");
Assert.AreEqual(0, bytesSent);
}
}
}
And my .moles file:
<Moles xmlns="http://schemas.microsoft.com/moles/2010/">
<Assembly Name="System.Net" />
</Moles>
Can someone pleas point out what is wrong with this and what to do to make it work. I know that there are other ways to mock out the Socket class for example with a wrapper class that implements my own interface but I'm only interested in doing this using Moles.
--Thanks Daniel
Lösung
In my experience, Moling the System assembly is quirky. Try this for the second line of your .moles file:
<Assembly Name="System" ReflectionOnly="true" />