Steve Chambers Steve Chambers - 1 year ago 267
C# Question

How to mock IDataRecord?

I'm trying to mock an

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
in place of
but it made no difference. This should be easy but I'm scratching my head - grateful for any advice!

Answer Source

You cannot mock static or extension methods since most of the mocking frameworks use dynamic proxies under the hood.

In your test, donot 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download