如何添加到模拟存储库

时间:2014-04-12 10:18:45

标签: c# .net asp.net-mvc-3 asp.net-mvc-4

我正在使用MVC 4创建一个应用程序。

我有以下Mock存储库

Mock<IProductRepository> mock = new Mock<IProductRepository>();
mock.Setup(m => m.Products).Returns(new List<Product>
{
    new Product { Name = "FootBall", Price=25 },
    new Product { Name = "Surf board", Price=179 },
    new Product { Name = "Running shoes", Price=25 },
}.AsQueryable());

ninjectKernel.Bind<IProductRepository>().ToConstant(mock.Object);

在我的控制器中,如何将新产品添加到此存储库?

public class ProductController:Controller     {         私有IProductRepository存储库;

    public ProductController(IProductRepository productRepository)
    {

        repository = productRepository;

    }

    public ViewResult List()
    {
        return View(repository.Products);
    }

    public ViewResult Add()
    {
       var newProduct = new Product
        {
            Name = "Sneakers", Price = 30
        };


      //how do I add this newProduct to the repository?

    }

}

我将以下内容添加到IProductRepository

 public interface IProductRepository
    {
        IQueryable<Product> Products();

        void AddProducts(Product product);
    }

 public class ProductRepository : IProductRepository
    {

        public IQueryable<Product> Products()
        {

           //how do I access the repo?


        }

        public void AddProducts(Product product)
        {


             //how do I access the repo?

        }
    }

1 个答案:

答案 0 :(得分:1)

在您的控制器中,您可以这样做:

    public class ProductRepository : IProductRepository
    {
        List<Product> data = new List<Product>
        {
            new Product { Name = "FootBall", Price=25 },
            new Product { Name = "Surf board", Price=179 },
            new Product { Name = "Running shoes", Price=25 }
        };

        public IQueryable<Product> Products()
        {

          return this.data.AsQueryable();

        }

        public void AddProducts(Product product)
        {
            this.data.Add(product);
        }
    }

如果要修改数据,则模拟不起作用,除非您在某处保留了对列表的引用,并且您在控制器的Add方法中访问了该列表。

<强>更新

为确保您使用相同的存储库,请将ninjectKernel始终返回相同的存储库。

ninjectKernel.Bind<IProductRepository>().ToConstant(new ProductRepository())