Reputation: 49
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
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