1

単体テストで「System.InvalidOperationException: The Connection is not open.」というエラーが発生し続けます。

テスト

[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 プロパティを使用するなど)。

したがって、私のアプローチは、このクラスの単体テストを実行しないことです。これは、事実上、サードパーティのライブラリのラッパーにすぎないためです。代わりに統合テストに進みます (テスト データベースを作成して接続します)。

于 2010-03-17T13:11:42.763 に答える