3

我正在尝试 Mock SqlConnection,本质上是IDbConnection.

为此,我为我的测试准备了我的模拟:

var dbConnectionMock = new Mock<IDbConnection>();

dbConnectionMock.Setup(x => x.CreateCommand()).Returns(new SqlCommand());

var repository = new XxxRepository(dbConnectionMock.Object);


存储库的构造函数设置此属性:

private IDbConnection Connection { get; set; }

然后Connection在调用 Db 时使用。

var command = Connection.CreateCommand();

command.Connection = Connection;// 这里失败了,因为 Connection 是 , 的IDbConnection代理IDbConnectionProxy类型

如何避免使用代理?

我想测试的只是那个command.ExecuteNonQuery()叫。

4

1 回答 1

5

问题可能是使用SqlConnection,因为它的Connection属性是SqlConnection类型的。尝试返回mockedIDbCommand

var dbCommandMock = new Mock<IDbCommand>();
dbCommandMock.Setup(dbc => dbc.ExecuteNonQuery());
dbConnectionMock.Setup(dbc => dbc.CreateCommand()).Returns(dbCommandMock.Object);

// ...

dbCommandMock.VerifyAll();
于 2012-09-06T12:32:47.983 回答