Created
April 8, 2012 06:20
-
-
Save jwatney/2335164 to your computer and use it in GitHub Desktop.
Moq extensions for mocking ADO.NET interfaces.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Data; | |
using Moq; | |
namespace Moq.DataExtensions { | |
public static class MockFactoryDataExtensions { | |
public static Mock<IDbCommand> CreateIDbCommand(this MockFactory factory) { | |
var command = factory.Create<IDbCommand>(); | |
command.SetupAllProperties(); | |
command.Setup(c => c.CreateParameter()).Returns(() => factory.CreateIDbDataParameter().Object); | |
command.Setup(c => c.Parameters).Returns(factory.CreateIDataParameterCollection().Object); | |
return command; | |
} | |
public static Mock<IDataParameterCollection> CreateIDataParameterCollection(this MockFactory factory) { | |
var list = new ArrayList(); // ArrayList more closely matches IDataParameterCollection. | |
var parameters = factory.Create<IDataParameterCollection>(); | |
parameters.Setup(p => p.Add(It.IsAny<IDataParameter>())).Returns((IDataParameter p) => list.Add(p)); | |
parameters.Setup(p => p[It.IsAny<int>()]).Returns((int i) => list[i]); | |
parameters.Setup(p => p.Count).Returns(() => list.Count); | |
return parameters; | |
} | |
public static Mock<IDbDataParameter> CreateIDbDataParameter(this MockFactory factory) { | |
var parameter = factory.Create<IDbDataParameter>(); | |
parameter.SetupAllProperties(); | |
return parameter; | |
} | |
public static Mock<IDataRecord> CreateIDataRecord(this MockFactory factory, params object[] fields) { | |
var record = factory.Create<IDataRecord>(); | |
for(var index = 0; index < fields.Length; index++) { | |
var column = fields[index]; | |
var type = column.GetType(); | |
var name = (string)type.GetProperty("Name").GetValue(column, null); | |
var value = type.GetProperty("Value").GetValue(column, null); | |
record.Setup(r => r.IsDBNull(index)).Returns(value == DBNull.Value); | |
record.Setup(r => r.GetOrdinal(name)).Returns(index); | |
record.Setup(r => r[index]).Returns(value); | |
} | |
return record; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment