Search code examples
c#testingmoqusing

How to use Moq to return a List of data or values?


Can anyone tell me how to return List of data using mock object using Moq framework and assigning the so returned list of data to another List<> variable.??


Solution

  • public class SomeClass
    {
        public virtual List<int> GimmeSomeData()
        {
            throw new NotImplementedException(); 
        }
    }
    
    [TestClass]
    public class TestSomeClass
    {
        [TestMethod]
        public void HowToMockAList()
        {
            var mock = new Mock<SomeClass>();
            mock.Setup(m => m.GimmeSomeData()).Returns(() => new List<int> {1, 2, 3});
            var resultList = mock.Object.GimmeSomeData();
            CollectionAssert.AreEquivalent(new List<int>{1,2,3},resultList);
        }
    }