问题
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