I want to mock the GreetingMessageHandler class in C# with Moq and Nunit in Visual Studio 2019 (version 16.8.4)
public class GreetingMessageHandler : AbstractServerMessageHandler
{
public GreetingMessageHandler(AbstractServerMessageHandler next) : base(next)
{
}
public override void InnerHandle(ServerSynchroMessage message)
{
IpInformation clientServerIpInformation = JsonConvert.DeserializeObject<IpInformation>(message.payload.body.ToString());
Collection<IpInformation> servers= message.serverReceiver.GetConnectedServer();
if (!MessageHandlingHelper.ServerExists(servers, clientServerIpInformation)) {
message.serverReceiver.ConnectToPeer(clientServerIpInformation);
}
}
}
And the Test trying to solve is to test the "InnerHandle" function that should on act run and test it if it runs atleast once. Here is my Code:
//arrange
var moqGreeting = new Mock<GreetingMessageHandler>();
var fakeGreet = new GreetingMessageHandler(null);
moqGreeting.Setup(x => x.InnerHandle(It.IsAny<ServerSynchroMessage>()));
// act
fakeGreet.InnerHandle(null);
// assert
moqGreeting.Verify(x => x.InnerHandle(It.IsAny<ServerSynchroMessage>()), Times.AtLeastOnce);
The error message I get for this is this:
Test method UnitTestProject.UnitTest1.GreetingMessageHandlerRun threw exception: Castle.DynamicProxy.InvalidProxyConstructorArgumentsException: Can not instantiate proxy of class: SychroClient.Communications.Server. Could not find a parameterless constructor.
To solve the parameterless constructor problem, I tried to give the functions null values to fake the parameters. But it didn´t work and now I am really desperate to find out why and how to solve this to work.
I figured it out in the end... I had to give the Mock a parameter(null) when creating it like this:
[TestMethod]
public void GreetingMessageHandlerRun()
{
// arrange
var moqGreeting = new Mock<GreetingMessageHandler>(null);
moqGreeting.Setup(x => x.InnerHandle(It.IsAny<ServerSynchroMessage>()));
// act
var fakeGreet = moqGreeting.Object;
fakeGreet.InnerHandle(null);
// assert
moqGreeting.Verify(x => x.InnerHandle(It.IsAny<ServerSynchroMessage>()), Times.AtLeastOnce);
}