-->

惩戒索引属性(Mocking indexed property)

2019-07-30 11:16发布

我写起订量使用单元测试。 我创建了一个模拟对象。 现在,当我尝试嘲笑其属性我得到错误“的表达式树不能包含索引属性”

这里是我的代码。

public Node GetNode(IMyInterface interface, string itemName)
{
    return interface.Items[itemName];
}

这里是单元测试

var expected = new Node();
var itemName = "TestName";
var mock = new Mock<IMyInterface>();
mock.Setup(f => f.Items[itemName]).Returns(expected);
var target = new MyClass();

var actual = target.GetNode(mock.Object, itemName);
Assert.AreEqual(expected, actual);

此行是给我的错误。

mock.Setup(f => f.Items[itemName]).Returns(expected);

我怎样才能MOQ此功能。

Answer 1:

接口是一个COM对象,并有得到的功能,所以不是使用索引使用get函数直接访问属性,

mock.Setup(f => f.get_Items(itemName)).Returns(expected); 


Answer 2:

在ASP.NET 2.2的核心使用起订量,在get_Items设置不起作用。 但这:

Mock<IConfiguration> configuration = new Mock<IConfiguration>();
configuration.Setup(x => x[key]).Returns(value);


文章来源: Mocking indexed property