Adding new items dynamically to IQueryable hard-coded fake repository

北城余情 提交于 2019-12-07 00:06:29

问题


Building an application, before using a real database, just to get things work I can first use a hard-coded list as a fake, in-memory repository:

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

How to add a method to this class for adding new, not hard-coded items in this list dynamically?


回答1:


Just keep the List<Product> in a field of type List<Product> instead of IQueryable<Product>:

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



回答2:


If you are going to Mock your repository for testing purposes then I'd suggest that you start by declaring an interface that encompasses the functions your expect from your repository. Then build your real and your 'fake' repository to implement that interface, otherwise you won't be able to easily substitute one for the other.

You'll find it pretty easy once you have that consistent interface, the functions will already be declared, i.e.

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


来源:https://stackoverflow.com/questions/3741756/adding-new-items-dynamically-to-iqueryable-hard-coded-fake-repository

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!