简体   繁体   English

模拟索引属性

[英]Mocking indexed property

I am writing unit tests using Moq. 我正在使用Moq编写单元测试。 I have created a mock object. 我创建了一个模拟对象。 Now when i try to mock its property i am getting error "An expression tree may not contain an indexed property" 现在,当我尝试模拟其属性时,我收到错误“表达式树可能不包含索引属性”

here is my code. 这是我的代码。

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

Here is the unit test 这是单元测试

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

This line is giving me error. 这条线给了我错误。

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

How can i moq this function. 我怎么能这个功能。

接口是一个COM对象并且有get函数,所以不使用索引器直接访问属性使用get函数,

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

Using Moq in ASP.NET Core 2.2, the get_Items setup does not work. 在ASP.NET Core 2.2中使用Moq,get_Items设置不起作用。 But this does: 但这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM