Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding new items dynamically to IQueryable hard-coded fake repository

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?

like image 840
rem Avatar asked Sep 18 '10 12:09

rem


2 Answers

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(); }
    }
}
like image 122
dtb Avatar answered Sep 18 '22 07:09

dtb


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;
     }
 }
like image 45
Lazarus Avatar answered Sep 20 '22 07:09

Lazarus