Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

testing

moq

using

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.??

like image 210
Neerajan Avatar asked May 02 '11 09:05

Neerajan


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);
    }
}
like image 172
Richard Banks Avatar answered Oct 20 '22 12:10

Richard Banks


@Richard Banks gave the correct answer. For completeness, if you want to use Moq v4 functional specifications and get rid of the .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();
}
like image 39
TrueWill Avatar answered Oct 20 '22 11:10

TrueWill