Hi,
I have a unit of work class which is as below:
public class UnitOfWork : IUnitOfWork, IDisposable
{
private readonly EFDbContext context;
private IGenericRepository<Category> _categoryRepository;
private IGenericRepository<Product> _productRepository;
#region Contructor
public UnitOfWork()
{
context = new EFDbContext();
}
#endregion
public IGenericRepository<Category> CategoryRepository
{
get
{
if (_categoryRepository == null)
{
_categoryRepository = new EFGenericRepository<Category>(context);
}
return _categoryRepository;
}
}
public IGenericRepository<Product> ProductRepository
{
get
{
if (_productRepository == null)
{
_productRepository = new EFGenericRepository<Product>(context);
}
return _productRepository;
}
}
}
I defined a new Interface, IPriceIncreaser. Purpose: Increase prices of all products in Product inventory
public class PriceIncreaser : IPriceIncreaser
{
private IUnitOfWork unitOfWork;
public PriceIncreaser(IUnitOfWork unitOfWorkParam)
{
unitOfWork = unitOfWorkParam;
}
public void IncreasePrice(decimal increaseAmount)
{
foreach (Product p in unitOfWork.ProductRepository.Get())
{
p.Price += increaseAmount;
}
}
}
Now, i want to unit test my repo, using Moq as the unit testing framework.
I've written the following unit test:
[TestMethod]
public void Can_Increase_Prices()
{
var mockProductRepo = new Mock<IGenericRepository<Product>>();
mockProductRepo.Object.Insert(new Product { Name = "MP", Description ="HI", Price = 2500 });
decimal initalProductTotalPrice = mockUnitOfWork.Object.ProductRepository.Get().Sum(p => p.Price);
decimal increaseAmount = 55;
PriceIncreaser target = new PriceIncreaser(mockUnitOfWork.Object);
target.IncreasePrice(increaseAmount);
Assert.AreNotEqual(initalProductTotalPrice, mockUnitOfWork.Object.ProductRepository.Get().Sum(p => p.Price));
}
But i'm getting an error when i run the test which says:
Cannot override Non-Virtual member ...ProductRepository
I realize from reading other threads that Moq will only mock Interfaces, and abstract methods/fields.
I want to know how i can now write a unit test, which mocks my Product repository, which is of type IGenericRepository<Product> contained within UnitOfWork.ProductRepository and UnitOfWork is-a IUnitOfWork.
Any and all suggestions appreciated.
Thanks.