通过依赖注入执行我的类函数

时间:2017-08-07 19:25:43

标签: c# asp.net-mvc unit-testing dependency-injection

我一直致力于将我的紧耦合方法转换为可以进行单元测试的方法,并在此处寻求一些建议。由于一些建议,我现在让我的方法通过它的单元测试 - 但是我现在发现我无法从我的应用程序中调用该方法。我曾经使用以下命令从控制器访问我的GetAllProductsFromCSV()方法:

    public ActionResult Index()
    {
        var products = new ProductsCSV();
        List<ProductItem> allProducts = products.GetAllProductsFromCSV();

        foreach (var product in allProducts)
        {
            if (string.IsNullOrEmpty(product.ImagePath))
            {
                product.ImagePath = "blank.jpg";
            }
        }

        return View(allProducts);
    }

方法如下:

public class ProductsCSV
{
    public List<ProductItem> GetAllProductsFromCSV()
    {
        var productFilePath = HttpContext.Current.Server.MapPath(@"~/CSV/products.csv");

        String[] csvData = File.ReadAllLines(productFilePath);

        List<ProductItem> result = new List<ProductItem>();

        foreach (string csvrow in csvData)
        {
            var fields = csvrow.Split(',');
            ProductItem prod = new ProductItem()
            {
                ID = Convert.ToInt32(fields[0]),
                Description = fields[1],
                Item = fields[2][0],
                Price = Convert.ToDecimal(fields[3]),
                ImagePath = fields[4],
                Barcode = fields[5]
            };
            result.Add(prod);
        }
        return result;
    }
}

我现在在ProductCSV类中进行了以下更改:

public class ProductsCSV
{
    private readonly IProductsCsvReader reader;

    public ProductsCSV(IProductsCsvReader reader = null)
    {
        this.reader = reader;
    }

    public List<ProductItem> GetAllProductsFromCSV()
    {
        var productFilePath = @"~/CSV/products.csv";
        var csvData = reader.ReadAllLines(productFilePath);
        var result = parseProducts(csvData);
        return result;
    }


    private List<ProductItem> parseProducts(String[] csvData)
    {
        List<ProductItem> result = new List<ProductItem>();

        foreach (string csvrow in csvData)
        {
            var fields = csvrow.Split(',');
            ProductItem prod = new ProductItem()
            {
                ID = Convert.ToInt32(fields[0]),
                Description = fields[1],
                Item = fields[2][0],
                Price = Convert.ToDecimal(fields[3]),
                ImagePath = fields[4],
                Barcode = fields[5]
            };
            result.Add(prod);
        }
        return result;
    }

以下课程&amp;接口:

public class DefaultProductsCsvReader : IProductsCsvReader
{
    public string[] ReadAllLines(string virtualPath)
    {
        var productFilePath = HostingEnvironment.MapPath(virtualPath);
        String[] csvData = File.ReadAllLines(productFilePath);
        return csvData;
    }
}

public interface IProductsCsvReader
{
    string[] ReadAllLines(string virtualPath);
}

正如我所说,方法GetAllProductsFromCSV上的单元测试现在成功完成但是当我尝试从我的控制器访问该方法时,我在GetAllProductsFromCSV中的reader.ReadAllLines调用上得到NullReferenceException。当我尝试从控制器中创建ProductsCSV的实例时,我有意义 - 我没有传递任何参数......但是该类的构造函数请求IProductsCsvReader。我无法弄清楚的是我现在如何实际调用该方法?我希望很清楚??

1 个答案:

答案 0 :(得分:5)

首先让更新ProductsCSV具有后备接口

public interface IProductsCSV {
    List<ProductItem> GetAllProductsFromCSV();
}

public class ProductsCSV : IProductsCSV {
    //...other code removed for brevity
}

控制器现在依赖于上面介绍的抽象,将其与具体实现与原始控制器分离。虽然是一个简化的例子,但它可以使控制器更易于维护和单独测试。

public class ProductsController : Controller {
    private readonly IProductsCSV products;

    public ProductsController(IProductsCSV products) {
        this.products = products;
    }

    public ActionResult Index() {
        List<ProductItem> allProducts = products.GetAllProductsFromCSV();    
        foreach (var product in allProducts) {
            if (string.IsNullOrEmpty(product.ImagePath)) {
                product.ImagePath = "blank.jpg";
            }
        }    
        return View(allProducts);
    }
}

请注意,除了products的创建方式之外,该操作与之前的操作完全匹配。

最后,现在控制器已被重构为依赖性反转,需要将框架配置为能够在请求时将依赖项注入控制器。

您最终可以使用您选择的库,但对于此示例,我使用的是他们在文档中使用的内容

ASP.NET MVC 4 Dependency Injection

别介意版本。实施是可转让的。

在上面的文档中,他们使用Unity作为他们的IoC容器。有许多容器库可供使用,因此请搜索您喜欢的容器库并使用它。

public static class BootStrapper {

    private static IUnityContainer BuildUnityContainer() {
        var container = new UnityContainer();

        //Register types with Unity
        container.RegisterType<IProductsCSV , ProductsCSV>();
        container.RegisterType<IProductsCsvReader, DefaultProductsCsvReader>();

        return container;
    }

    public static void Initialise() {
        //create container
        var container = BuildUnityContainer();
        //grab the current resolver
        IDependencyResolver resolver = DependencyResolver.Current;
        //create the new resolver that will be used to replace the current one
        IDependencyResolver newResolver = new UnityDependencyResolver(container, resolver);
        //assign the new resolver.
        DependencyResolver.SetResolver(newResolver);
    }
}

public class UnityDependencyResolver : IDependencyResolver {
    private IUnityContainer container; 
    private IDependencyResolver resolver;

    public UnityDependencyResolver(IUnityContainer container, IDependencyResolver resolver) {
        this.container = container;
        this.resolver = resolver;
    }

    public object GetService(Type serviceType) {
        try {
            return this.container.Resolve(serviceType);
        } catch {
            return this.resolver.GetService(serviceType);
        }
    }

    public IEnumerable<object> GetServices(Type serviceType) {
        try {
            return this.container.ResolveAll(serviceType);
        } catch {
            return this.resolver.GetServices(serviceType);
        }
    }
 }

您可以在启动代码中调用上述引导程序。

例如

protected void Application_Start() {
    AreaRegistration.RegisterAllAreas();    
    WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    Bootstrapper.Initialise(); //<-- configure DI

    AppConfig.Configure();
}

所以现在,当框架必须创建ProductsController时,它将知道如何初始化和注入控制器的依赖项。