moq icon indicating copy to clipboard operation
moq copied to clipboard

Returns not working on UdpClient.Receive() method.

Open mnicic opened this issue 9 years ago • 2 comments

Returns not working on UdpClient.Receive() method.

Class code:

var remoteEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0);
var receiveBytes = this.udpClient.Receive(ref remoteEndPoint);
var responseData = Encoding.ASCII.GetString(receiveBytes);

Unit testing code:

var remoteEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0);
var b = Encoding.ASCII.GetBytes("responseData");
udpClientMock.Setup(x => x.Receive(ref remoteEndPoint)).Returns(b);

Nothing is returned (byte[]). Exception is "The following setups were not matched: IUdpClientExtended x => x.Receive(0.0.0.0:0)". It is also problem with replacing Returns with Throws.

With Strict mode, the error says: "Invocation failed with mock behavior Strict. All invocations on the mock must have a corresponding setup."

mnicic avatar Sep 08 '17 11:09 mnicic

I am not sure that I understand how your two repro code blocks are supposed to work and be related to one another. It seems incomplete. Could you please post a minimally complete code example that leads to the error message you're describing?

stakx avatar Sep 08 '17 15:09 stakx

In absence of actual repro code, I will just guess you're doing something like the following (which produces the same error):

public interface IUdpClientExtended
{
    byte[] Receive(ref IPEndPoint endpoint);
}

var mock = new Mock<IUdpClientExtended>(MockBehavior.Strict);
var endpoint = new IPEndPoint(IPAddress.Any, 0);
mock.Setup(_ => _.Receive(ref endpoint)).Returns(Encoding.UTF8.GetBytes("Hello world"));

var differentEndpoint = new IPEndPoint(IPAddress.Any, 0);
var response = mock.Object.Receive(ref differentEndpoint);

This doesn't work because the instance of IPEndPoint you're passing to your mock (differentEndpoint) is not the exact same instance that you used during the mock setup (even though both have the same value).

AFAIK, Moq doesn't currently support It.IsAny<T> for ref parameters. So the solution here is either of these:

  • Change the definition of IUdpClientExtended so that Receive's parameter is by value instead of ref.
  • Use the exact same instance of IPEndPoint to your mock that you're using during the setup.

If the above doesn't help you, or my repro code doesn't match your scenario, please report back and we can reopen this issue.

stakx avatar Sep 16 '17 14:09 stakx