Steve Chambers Steve Chambers - 1 month ago 23
C# Question

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!

Answer

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.

Comments