在使用真实数据库之前构建一个应用程序,只是为了让事情有效我可以先使用硬编码列表作为虚假的内存存储库:
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; }
}
}
如何向此类添加方法,以便动态地在此列表中添加新的,而非硬编码的项目?
答案 0 :(得分:13)
只需保留列表&lt;产品&gt;在List&lt; Product&gt;类型的字段中而不是IQueryable&lt; Product&gt;:
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(); }
}
}
答案 1 :(得分: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;
}
}