Unit Test For NpgsqlCommand With Rhino Mocks

Posted by J Pollack on Stack Overflow See other posts from Stack Overflow or by J Pollack
Published on 2010-03-16T09:32:25Z Indexed on 2010/03/16 9:36 UTC
Read the original article Hit count: 900

Filed under:
|
|
|
|

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.

© Stack Overflow or respective owner

Related posts about c#

Related posts about rhino-mocks