1

我的单元测试不断收到以下错误:“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 服务器的连接。

4

1 回答 1

1

您的方法存在一些问题:

  1. NpgsqlConnection 是一个类,我的猜测是状态属性不是虚拟的 - 所以你创建的存根是行不通的(正如你所注意到的0。我认为没有任何解决方法。
  2. 在您的测试中,您实际上是在测试 NpgsqlCommand 的内部(因为您在 ExecuteProcedure 方法中创建了一个具体的实现)。这是一个第三方类,你应该只假设它记录的接口,而不是实现细节(例如,它在连接上使用 State 属性)

所以我的方法是不对这个类运行任何单元测试,因为它实际上只是一个 3rd 方库的包装器。改为进行集成测试(因此创建一个测试数据库并连接到它)。

于 2010-03-17T13:11:42.763 回答