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

Can someone tell me how to return a list of data using a mock using the Moq infrastructure and assign the returned list of data to another variable List <>.

+4
source share
2 answers
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); } } 
+6
source

@ Richard Banks gave the correct answer. For completeness, if you want to use the functional specifications of Moq v4 and get rid of .Object:

 void Main() { var list = new List<int> { 1, 2, 3 }; ISomeInterface implementation = Mock.Of<ISomeInterface>(si => si.GimmeSomeData() == list); List<int> resultList = implementation.GimmeSomeData(); foreach (int i in resultList) { Console.WriteLine(i); } } public interface ISomeInterface { List<int> GimmeSomeData(); } 
+1
source

All Articles