I came across some weird behavior when trying to simplify the creation of a rather complex expression tree for installing / checking compliance using moq.
Suppose I mock the simple interface defined below
public interface IService { int Send(int value); }
The following code is 5 tests. One test for each of mockSender.Setup(...)
. Can someone explain why the tests marked as unsuccessful will not work?
[Test] public void TestInlineSetup() { const int expected = 5; var mockSender = new Mock<IService>(MockBehavior.Loose); //passes mockSender.Setup(s => s.Send(It.IsAny<int>())).Returns(expected); //fails var sendMatch = It.IsAny<int>(); mockSender.Setup(s => s.Send(sendMatch)).Returns(expected); //passes mockSender.Setup(s => s.Send(SendMatchFromMethod())).Returns(expected); //fails var sendMatch = SendMatchFromMethod(); mockSender.Setup(s => s.Send(sendMatch)).Returns(expected); //fails (this is somewhat contrived, but I have reasons for wanting to curry this) mockSender.Setup(s => s.Send(SendMatchFromCurriedMethod()())).Returns(expected); Assert.That(mockSender.Object.Send(expected), Is.EqualTo(expected)); } public static int SendMatchFromMethod() { return It.IsAny<int>(); } public static Func<int> SendMatchFromCurriedMethod() { return () => It.IsAny<int>(); }
Edit: I know about Mock.Of <..> (..) and usually prefer to use it, but in this case this is not an option.
source share