2010-09-18 48 views
7

構建應用程序,使用一個真正的數據庫之前,只是爲了得到工作的事情,我可以先用硬編碼的列表爲假,在記憶庫:添加新項動態到IQueryable的硬編碼的假庫

public class FakeProductsRepository 
{ 
    private static IQueryable<Product> fakeProducts = new List<Product> { 
     new Product{ ProductID = "xxx", Description = "xxx", Price = 1000}, 
     new Product{ ProductID = "yyy", Description = "xxx", Price = 2000}, 
     new Product{ ProductID = "zzz", Description = "xxx", Price = 3000} 
    }.AsQueryable(); 

    public IQueryable<Product> Products 
    { 
     get { return fakeProducts; } 
    } 
} 

如何在此類中添加一個方法,以便在此列表中動態添加新的非硬編碼項目?

回答

13

只要保持列表<產品>類型列表中的一個字段<產品>而不是IQueryable的<產品>:

public class FakeProductsRepository 
{ 
    private readonly List<Product> fakeProducts = new List<Product> 
    { 
     new Product { ProductID = "xxx", Description = "xxx", Price = 1000 }, 
     new Product { ProductID = "yyy", Description = "xxx", Price = 2000 }, 
     new Product { ProductID = "zzz", Description = "xxx", Price = 3000 }, 
    }; 

    public void AddProduct(string productID, string description, int price) 
    { 
     fakeProducts.Add(new Product 
     { 
      ProductID = productID, 
      Description = description, 
      Price = price, 
     }); 
    } 

    public IQueryable<Product> Products 
    { 
     get { return fakeProducts.AsQueryable(); } 
    } 
} 
+0

謝謝!以及如何構建** AddProduct **方法,使其包含作爲參數而不是對象** Product **,但是變量:** ProductID **,**說明**和** Price **? – rem 2010-09-18 13:07:13

+0

在AddProduct內使用「'新產品」。 – 2010-09-18 13:17:41

5

如果你要嘲笑你的測試目的版本庫,那麼我會建議你首先聲明一個包含你期望從你的倉庫中獲得的函數的接口。然後建立你的真實和你的'假'存儲庫來實現這個接口,否則你將無法輕鬆地替換另一個。

你會發現它很簡單,一旦你有一個一致的界面,功能就已經被宣告,即

public interface IRepository { 
    IQueryable<Products> GetAllProducts(); 
    Product AddProduct(Product Product); 
} 

public class FakeRepository : IRepository { 
    private static IList<Product> fakeProducts = new List<Product> { 
     new Product{ ProductID = "xxx", Description = "xxx", Price = 1000}, 
     new Product{ ProductID = "yyy", Description = "xxx", Price = 2000}, 
        new Product{ ProductID = "zzz", Description = "xxx", Price = 3000} 
    }; 

    public IQueryable<Product> GetAllProducts() { 
     return fakeProducts.AsQueryable(); 
    } 

    public Product Add(Product Product) { 
     fakeProducts.Add(Product); 
     return Product; 
    } 
} 
+0

接口非常棒 – bkwdesign 2015-08-13 18:22:24