对于下面的方法,我想传递一个模拟的DbProviderFactories
类,但不能,因为它是一个静态类:
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;
}
}
如何测试我的代码/如何模拟DbProviderFactories
您可以为DbProviderFactory
创建自己的非静态包装器,实现自己的接口并调用静态方法:
public interface IDbProviderFactories
{
DbProviderFactory GetFactory(string name);
}
public class MyDbProviderFactories : IDbProviderFactories
{
public DbProviderFactory GetFactory(string name)
{
return DbProviderFactories.GetFactory(name);
}
}
如果您现在将其注入到暴露GetConnection()
的类中,您可以根据需要模拟接口的实现。