2014-04-12 55 views
0

我創建使用MVC 4如何添加到一個模擬庫

一個應用程序,我有以下模擬庫

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); 

在我CONTROLER如何添加一個新的產品,以這個倉庫?

public class ProductController:Controller { private IProductRepository repository;

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? 

     } 
    } 
+0

「IProductRepository」有哪些方法? –

+0

目前沒有,我已經添加了兩種方法..查看代碼更新..但我如何創建它們的具體實例?我如何參考存儲庫? – user2206329

+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())

+0

沒有這樣的方法叫Add – user2206329

+0

我的不好,只是調用'AddProducts' –

+0

但AddProducts尚未實現... – user2206329

相關問題