谁能告诉我如何使用Moq框架使用模拟对象返回数据列表,并将返回的数据列表分配给另一个List<>变量。
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);
}
}
@Richard Banks给出了正确答案。为了完整起见,如果您想使用Moq v4功能规范并去掉.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();
}