{"id":65,"date":"2016-09-06T19:07:03","date_gmt":"2016-09-06T23:07:03","guid":{"rendered":"http:\/\/langstonsoftware.com\/?p=65"},"modified":"2016-09-06T15:07:49","modified_gmt":"2016-09-06T19:07:49","slug":"moq-cant-setup-methods-with-anonymous-object-arguments","status":"publish","type":"post","link":"https:\/\/langstonsoftware.com\/2016\/09\/06\/moq-cant-setup-methods-with-anonymous-object-arguments\/","title":{"rendered":"Moq can’t setup methods with anonymous object arguments"},"content":{"rendered":"
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.<\/p>\n
\r\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\r\nusing Moq;\r\n\/\/Moq version 4.0.10827\r\n\r\nnamespace AX.Test.Common\r\n{\r\n public class ExampleAnonObjMockSetup\r\n {\r\n public interface IThing\r\n {\r\n string DoIt<T>(T it);\r\n }\r\n\r\n public class Subject\r\n {\r\n private readonly IThing _thing;\r\n\r\n public Subject(IThing thing)\r\n {\r\n _thing = thing;\r\n }\r\n\r\n public string Execute()\r\n {\r\n var param = new\r\n {\r\n Foo = "bar",\r\n Baz = 23\r\n };\r\n return _thing.DoIt(param);\r\n }\r\n }\r\n\r\n [TestClass]\r\n public class SubjectTest\r\n {\r\n [TestMethod]\r\n public void Test()\r\n {\r\n var mockThing = new Mock<IThing>();\r\n mockThing.Setup(t => t.DoIt(It.IsAny<object>()))\r\n .Returns("expectedResult");\r\n\r\n var subject = new Subject(mockThing.Object);\r\n var result = subject.Execute();\r\n\r\n Assert.AreEqual("expectedResult", result);\r\n \/\/Assert.AreEqual failed. Expected:<expectedResult>. Actual:<(null)>\r\n }\r\n }\r\n }\r\n}\r\n<\/pre>\nI’ve played with this code some more this Gist: https:\/\/gist.github.com\/thomaslangston\/46734b4577d1d3eac8c9d2c331f9e278<\/a><\/p>\n