views:

103

answers:

2

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?

+4  A: 

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(); }
    }
}
dtb
Thanks! And how to build the **AddProduct** method so as it contains as parameter not the object **Product**, but the variables: **ProductID**, **Description**, and **Price**?
rem
Use "`new Product`" inside `AddProduct`.
Ben Voigt
+1  A: 

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