DotNetSurfers

Latish Sehgal's Blog

Mocking an Indexed Property Using MOQ

I was writing unit tests for some code today that updated the value of an indexed property, and I could not find a straightforward way to do this with MOQ. For regular properties, you can enable value tracking by calling SetupProperty() or SetupProperties() on the mock object, but this does not seem to work for indexed properties. So I worked around this by using the Callback() method. Below is an example of the approach I took.  Here I am using a dictionary that contains ages and I am setting up value tracking for a person named Sara.

        private IDictionary<string, int> _ages;




 




        [TestInitialize]




        public void Setup()




        {




            var mockDictionary = new Mock<IDictionary<string, int>>();




            mockDictionary.SetupSet(m => m["Sara"] = It.IsAny<int>())




                .Callback((string name, int value) => mockDictionary




                                            .SetupGet(m => m["Sara"])




                                            .Returns(value));




            _ages = mockDictionary.Object;




        }




 




        [TestMethod]




        public void Test_Indexed_Property_Using_MOQ()




        {




            _ages["Sara"] = 15;




            IncrementAge(_ages,"Sara");




            Assert.AreEqual(16,_ages["Sara"]);




        }




 




        static void IncrementAge(IDictionary<string,int> ages,string personName)




        {




            ages[personName] = ages[personName] + 1;




        }

Update: Looks like Bertrand Le Roy had already blogged about a similar solution.

Comments