Дразнить удаление с помощью репозитория и UnitOfWork - PullRequest
1 голос
/ 18 марта 2020

Используя Unit, я пытаюсь настроить тест, в котором я могу удалить запись из своего списка Mock, чтобы проверить реализацию в моем CustomerManager.

Моем репозитории:

public class Repository<T> : IRepository<T> where T : ModelBase
{
    private readonly CustomerDbContext _context;

    public Repository(CustomerDbContext context)
    {
        if (_context == null)
            throw new ArgumentNullException(nameof(context));
        _context = context;
    }

    public async Task Delete(int id, bool softDelete = true)
    {
        var entity = await GetById(id);
        if (entity == null) return;

        if (softDelete)
        {
            entity.IsDeleted = true;
            Save(entity);
        }
        else
            _context.Set<T>().Remove(entity);
    }

    public async Task<T> GetById(int id)
    {
        return await _context.Set<T>().FirstOrDefaultAsync(t => t.Id == id).ConfigureAwait(false);
    }

    public void Save(T entity)
    {
        if (entity.Id == 0)
            _context.Set<T>().Add(entity);
        else
            _context.Entry(entity).State = EntityState.Modified;
    }
}

Моя единица работы:

public class CustomerUnitOfWork : IUnitOfWork
{
    public CustomerDbContext Context { get; }

    public async Task<int> Commit()
    {
        foreach(var item in Context.ChangeTracker.Entries().Where(e => e.State == EntityState.Added || e.State == EntityState.Modified))
        {
            if (!(item.Entity is ModelBase entity))
                continue;
            if (item.State == EntityState.Added)
            {
                entity.CreatedDate = DateTime.UtcNow;
            }
            entity.ModifiedDate = DateTime.UtcNow;                
        }
        return await Context.SaveChangesAsync();
    }
}

Мой менеджер:

public class CustomerManager : ICustomerManager
{
    private readonly IRepository<Models.Customer> _customerRepository;
    protected readonly IUnitOfWork _unitOfWork;

    public CustomerManager(IRepository<Models.Customer> customerRepository, IUnitOfWork unitOfWork)
    {
        _customerRepository = customerRepository;
        _unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
    }

    public async Task<int> Delete(int id, bool softDelete = true)
    {
        await _customerRepository.Delete(id, softDelete);
        return await _unitOfWork.Commit();
    }

    public async Task<Models.Customer> GetById(int id)
    {
        return await _customerRepository.GetById(id);
    }
}

В моем модульном тесте я настраиваю конструктор как this:

private ICustomerManager MockManager;
private Mock<IUnitOfWork> UnitOfWork;
private List<Models.Customer> Customers;
Mock<IRepository<Models.Customer>> MockRepository;

public CustomerTest()
{
    MockRepository = new Mock<IRepository<Models.Customer>>();
    UnitOfWork = new Mock<IUnitOfWork>();
    Customers = new List<Models.Customer>()
    {
        new Models.Customer
        {
            Id = 1,
            Name = "Foo",
            City = "Baltimore",
            Company = "Foo Company"
        },
        new Models.Customer
        {
            Id = 2,
            Name = "Bar",
            City = "Owings Mills",
            Company = "Bar Company"
        }
    };
    MockRepository.Setup(repo => repo.GetAll()).ReturnsAsync(Customers);
    MockRepository.Setup(repo => repo.GetById(It.IsAny<int>())).ReturnsAsync((int i) => Customers.SingleOrDefault(c => c.Id == i));
    MockRepository.SetupAllProperties();
    MockManager = new CustomerManager(MockRepository.Object, UnitOfWork.Object);

}

В моем методе тестирования я хочу удалить первый объект в моем списке тестов.

public async Task ShouldDelete()
{
    var countBeforeDelete = Customers.Count();
    var countAfterDelete = await MockManager.Delete(1, true);
    Assert.Equal(countBeforeDelete, countAfterDelete);
}

Однако CountAfterDelete всегда возвращает 0. Я не уверен, что я делаю не так.

1 Ответ

2 голосов
/ 18 марта 2020

Метод Delete вашего менеджера возвращает await _unitOfWork.Commit();

. По умолчанию макет IUnitOfWork возвращает значение по умолчанию (int), равное 0.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...