简体   繁体   English

如何模拟 IDataRecord?

[英]How to mock IDataRecord?

I'm trying to mock an IDataRecord using Moq.我正在尝试使用 Moq 模拟IDataRecord

The mock was created as follows:模拟创建如下:

Mock<IDataRecord> mockDataRecord = new Mock<IDataRecord>();

The line under test is:被测线路是:

DateTime timestamp = dataRecord.GetValueOrDefault<DateTime>("QUEUE_ADD_TS");

Have tried:试过:

mockDataRecord.Setup(r => r.GetValueOrDefault<DateTime>("QUEUE_ADD_TS")).Returns(now);

...but it gives a runtime error: ...但它给出了一个运行时错误:

Expression references a method that does not belong to the mocked object: r => r.GetValueOrDefault("QUEUE_ADD_TS")表达式引用了一个不属于模拟对象的方法: r => r.GetValueOrDefault("QUEUE_ADD_TS")

Also tried substituting It.IsAny<String>() in place of "QUEUE_ADD_TS" but it made no difference.还尝试用It.IsAny<String>()代替"QUEUE_ADD_TS"但没有区别。 This should be easy but I'm scratching my head - grateful for any advice!这应该很容易,但我正在挠头 - 感谢您的任何建议!

I do it like this, quick and dirty:我这样做,又快又脏:

Mock<IDataRecord> dataRecord = new Mock<IDataRecord>();
dataRecord.Setup(column => column["applicationno"]).Returns("foobar");
dataRecord.Setup(column => column["numberOfApplications"]).Returns(12);

You cannot mock static or extension methods since most of the mocking frameworks use dynamic proxies under the hood.您不能模拟静态或扩展方法,因为大多数模拟框架在后台使用动态代理。

In your test, do not stub the extension method.在您的测试中,不要存根扩展方法。 Instead, stub the original method itself, like:相反,存根原始方法本身,例如:

mockDataRecord.Setup(r => r.GetValue<DateTime>("QUEUE_ADD_TS")).Returns(now);

You should test the extension method separately, like:您应该单独测试扩展方法,例如:

  1. Stub the GetValue method and asserting that GetValueOrDefault returns the stubbed value.存根 GetValue 方法并断言 GetValueOrDefault 返回存根值。

  2. Donot stub GetValue method, and assert that GetValueOrDefault returns the default value.不要存根 GetValue 方法,并断言 GetValueOrDefault 返回默认值。

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

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