对于下面的方法,我想传递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()的类中,则可以根据需要模拟接口的实现。

09-04 05:41