使用 Rhino Mocks 对 NpgsqlCommand 进行单元测试
我的单元测试不断收到以下错误:“System.InvalidOperationException:连接未打开。”
测试
[TestFixture]
public class Test
{
[Test]
public void Test1()
{
NpgsqlConnection connection = MockRepository.GenerateStub<NpgsqlConnection>();
// Tried to fake the open connection
connection.Stub(x => x.State).Return(ConnectionState.Open);
connection.Stub(x => x.FullState).Return(ConnectionState.Open);
DbQueries queries = new DbQueries(connection);
bool procedure = queries.ExecutePreProcedure("201003");
Assert.IsTrue(procedure);
}
}
待测
using System.Data;
using Npgsql;
public class DbQueries
{
private readonly NpgsqlConnection _connection;
public DbQueries(NpgsqlConnection connection)
{
_connection = connection;
}
public bool ExecutePreProcedure(string date)
{
var command = new NpgsqlCommand("name_of_procedure", _connection);
command.CommandType = CommandType.StoredProcedure;
NpgsqlParameter parameter = new NpgsqlParameter {DbType = DbType.String, Value = date};
command.Parameters.Add(parameter);
command.ExecuteScalar();
return true;
}
}
代码您将如何使用 Rhino Mocks 3.6 测试代码?
PS。 NpgsqlConnection 是到 PostgreSQL 服务器的连接。
My unit test keeps getting the following error: "System.InvalidOperationException: The Connection is not open."
The Test
[TestFixture]
public class Test
{
[Test]
public void Test1()
{
NpgsqlConnection connection = MockRepository.GenerateStub<NpgsqlConnection>();
// Tried to fake the open connection
connection.Stub(x => x.State).Return(ConnectionState.Open);
connection.Stub(x => x.FullState).Return(ConnectionState.Open);
DbQueries queries = new DbQueries(connection);
bool procedure = queries.ExecutePreProcedure("201003");
Assert.IsTrue(procedure);
}
}
Code Under Test
using System.Data;
using Npgsql;
public class DbQueries
{
private readonly NpgsqlConnection _connection;
public DbQueries(NpgsqlConnection connection)
{
_connection = connection;
}
public bool ExecutePreProcedure(string date)
{
var command = new NpgsqlCommand("name_of_procedure", _connection);
command.CommandType = CommandType.StoredProcedure;
NpgsqlParameter parameter = new NpgsqlParameter {DbType = DbType.String, Value = date};
command.Parameters.Add(parameter);
command.ExecuteScalar();
return true;
}
}
How would you test the code using Rhino Mocks 3.6?
PS. NpgsqlConnection is a connection to a PostgreSQL server.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的方法存在一些问题:
所以我的方法是不运行此类的任何单元测试,因为它实际上只是第三方库的包装器,而是进行集成测试(因此创建一个测试数据库并连接到它)。 。
There are a few issues with your approach:
So my approach would be to not run any unit tests for this class, because its effectively just a wrapper around a 3rd party library. Go for integration tests instead (so create a test database and connect to it).