mercredi 30 mars 2016

Generic Repository doesn't add entity to context when testing

I'm creating a GenericRepository with EF and writing Unit Tests for the first time. Tests for GetAll() and Update() passed but Add() and Delete() failed. Why doesn't it Add? I'm pulling my hair out because it's one line of code and I couldn't figure it out.

Any advice is welcomed.

public class GenericDataRepository<T, C> : IGenericDataRepository<T, C> where T : class where C : DbContext, new() {

    protected C _context;
    protected IDbSet<T> _dbSet;

    public GenericDataRepository() {
        _context = new C();
        _dbSet = _context.Set<T>();
    }

    public GenericDataRepository(C context) {
        _context = context;
        _dbSet = context.Set<T>();
    }

    public virtual IQueryable<T> GetAll() {
        return _dbSet.AsQueryable<T>();
    }

    public virtual T Add(T entity) {
        return _dbSet.Add(entity);
    }

    public virtual void Update(T entity) {
        _context.Entry(entity).State = EntityState.Modified;
    }

    public virtual T Delete(T entity) {
        return _dbSet.Remove(entity);
    }

    public virtual void Save() {
        _context.SaveChanges();
    }

}

Tests

static IQueryable<Customer> data;
[SetUp]
    public void Init() {
        data = new List<Customer> {
            new Customer {
                CUSTOMER = "333",
                CUSTOMERNAME = "no name"
            },
            new Customer {
                CUSTOMER = "555",
                CUSTOMERNAME = "test name"
            }
        }.AsQueryable();
    }
[Test]
    public void Add_Should_AddGenericT() {

        var mockSet = NSubstituteUtils.CreateMockDbSet<Customer>(data);
        var mockContext = Substitute.For<MyEntities>();
        mockContext.Set<Customer>().Returns(mockSet);

        var repo = new GenericDataRepository<Customer, MyEntities>(mockContext);

        var customer = new Customer {
            CUSTOMER1 = "123",
            CUSTOMERNAME = "test name"
        };
        var result = repo.Add(customer);        // issue here: result returns null which should be a Customer
        repo.Save();

        var customerList = repo.GetAll().ToList();
        Assert.AreEqual(3, customerList.Count); // failed. Expected 3 but was 2
    }

Aucun commentaire:

Enregistrer un commentaire