简体   繁体   English

使用Moq模拟IDataRecord

[英]Mock IDataRecord using Moq

I am attempting to Mock an IDataRecord interface. 我试图模拟IDataRecord接口。

So far I have: 到目前为止,我有:

        var mockIDataRecord = new Mock<IDataRecord>();
        mockIDataRecord.SetupGet(c => c["id"]).Returns(7);
        var z = mockIDataRecord["id"];

But Visual Studio throws a compilation error on the last line of that: 但是Visual Studio在最后一行抛出了一个编译错误:

Error 2 Cannot apply indexing with [] to an expression of type 'Moq.Mock <System.Data.IDataRecord>' 错误2无法将带有[]的索引应用于类型为“Moq.Mock <System.Data.IDataRecord>”的表达式

Any suggestions? 有什么建议?

The error is what visual studio says. 错误是视觉工作室所说的。 You are applying indexing to instance of Mock class, not its generic parameter ( IDataRecord in your case). 您正在将索引应用于Mock类的实例,而不是其通用参数(在您的情况下为IDataRecord )。 Use Mock.Object Property that will return IDataRecord and apply indexing to it 使用将返回IDataRecord并对其应用索引的Mock.Object属性

var z = mockIDataRecord.Object["id"];

You have created a mock of an object (of type IDataRecord). 您已经创建了一个对象的模拟(IDataRecord类型)。 However you are trying to access mockIDataRecord[id] which implies that mockIDataRecord is a collection (Array?). 但是,您正在尝试访问mockIDataRecord [id],这意味着mockIDataRecord是一个集合(Array?)。

The type mismatch is probably what is causing the error. 类型不匹配可能是导致错误的原因。

Can you try something like this instead (I haven't checked the syntax): 你可以尝试这样的东西(我没有检查语法):

var mockIDataRecord = new Mock<IDataRecord[]>();

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

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