vendredi 26 février 2016

Unit testing with dbset

looking for some advice on how to unit test something. I have an interface below

public interface IProductContext
{
    DbSet<IProduct> Products { get; set; }
    int SaveChanges();
}

With the class below that implements it as well as inherits from DBContext for the purposes of being able to use entity framework

public class ProductContext : DbContext, IProductContext
{
    public ProductContext()
        :base(@"Server=aaa;Database=bbbTrusted_Connection=True"){}
    public virtual DbSet<IProduct> Products { get; set; }
    public override int SaveChanges()
    {
        return this.SaveChanges();
    }
}

I created the fake object below to pass into the repository which is the thing im trying to test

public class ProductContextFake : IProductContext
{
    public DbSet<IProduct> Products {get;set;}
    public ProductContextFake()
    {          
        Products = new DbSet<Product>();

        Products.Add(new Product { ProductId = 1, ProductName = "1" });
        Products.Add(new Product { ProductId = 2, ProductName = "2" });
        Products.Add(new Product { ProductId = 3, ProductName = "3" });
    } /.... }

The problem is that I can't new up the Products, so wondering if there is a better way. Also the reason I have Products in the interface is so that when i call the IProductContext from the repo, I can just call something like context.Products.FirstOrDefault(p => p.ProductId == id); without worrying if its real or fake context

    [TestMethod]
    public void GetById_ItemFound_ReturnsTrue()
    {
        ProductRepository productRepository = new ProductRepository(new ProductContextFake());
        var product = productRepository.GetById(1);

        Assert.IsNotNull(product);
        Assert.AreEqual(product.ProductName, string.Format(CultureInfo.InvariantCulture, "1"));
    }

Aucun commentaire:

Enregistrer un commentaire