Something frustrating I learned today about my favorite Mocking tool today, or at least in version 4.0 that I have installed, it can’t handle anonymous objects in method parameters. This is very depressing in web programming where it doesn’t make much sense to create a static DTO type for every version of a API call.
using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; //Moq version 4.0.10827 namespace AX.Test.Common { public class ExampleAnonObjMockSetup { public interface IThing { string DoIt<T>(T it); } public class Subject { private readonly IThing _thing; public Subject(IThing thing) { _thing = thing; } public string Execute() { var param = new { Foo = "bar", Baz = 23 }; return _thing.DoIt(param); } } [TestClass] public class SubjectTest { [TestMethod] public void Test() { var mockThing = new Mock<IThing>(); mockThing.Setup(t => t.DoIt(It.IsAny<object>())) .Returns("expectedResult"); var subject = new Subject(mockThing.Object); var result = subject.Execute(); Assert.AreEqual("expectedResult", result); //Assert.AreEqual failed. Expected:<expectedResult>. Actual:<(null)> } } } }
I’ve played with this code some more this Gist: https://gist.github.com/thomaslangston/46734b4577d1d3eac8c9d2c331f9e278
Others have reported that this behavior is fixed in Moq 4.1, but I have not yet verified. http://stackoverflow.com/questions/34185691/moq-setup-method-with-generic-anonymous-parameter