简体   繁体   中英

How to mock IDataRecord?

I'm trying to mock an IDataRecord using Moq.

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

Also tried substituting It.IsAny<String>() in place of "QUEUE_ADD_TS" but it made no difference. 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.

  2. Donot stub GetValue method, and assert that GetValueOrDefault returns the default value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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