user2151264
user2151264

Reputation: 49

How to test DbProviderFactories using nunit

For the below method I want to pass in a mock of the DbProviderFactories class but can't because it's a static class:

    private DbConnection GetConnection()
     {
        var dbProviderFactory = DbProviderFactories.GetFactory(_name);

            try
            {
                var dbConnection = dbProviderFactory.CreateConnection();
                if (dbConnection == null) return null;
                dbConnection.ConnectionString = _connectionString;
                return dbConnection;
            }
            catch (Exception)
            {
                return null;
            }
        }

How can I test my code / how can I mock DbProviderFactories?

Upvotes: 2

Views: 482

Answers (1)

Steve Lillis
Steve Lillis

Reputation: 3256

You could create your own non-static wrapper for DbProviderFactory that implements your own interface and calls the static method:

public interface IDbProviderFactories
{
    DbProviderFactory GetFactory(string name);
}

public class MyDbProviderFactories : IDbProviderFactories
{
    public DbProviderFactory GetFactory(string name)
    {
        return DbProviderFactories.GetFactory(name);
    }
}

If you now inject this into your class that exposes GetConnection() you can mock an implementation of the interface as needed.

Upvotes: 1

Related Questions