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

荒凉一梦 提交于 2020-01-02 02:59:07

问题


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


回答1:


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);
    }
}



回答2:


@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();
}


来源:https://stackoverflow.com/questions/5855755/how-to-use-moq-to-return-a-list-of-data-or-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!