Recommand · October 22, 2021 0

How Can I Mock an Interface Which Contain Db Context?

I try to mock for xUnit but couldn’t. So how can I mock this Interface to add services because another repository is using IUnitOfWork interface.

Interface

namespace Insurance.Api.IRepository
{
    public interface IUnitOfWork : IDisposable
    {
        IGenericRepository<Surcharge> Surcharges { get; }
        Task Save();
    }
}

Class

using System;
using System.Threading.Tasks;
using Insurance.Api.Data;
using Insurance.Api.IRepository;

namespace Insurance.Api.Repository
{
    public class UnitOfWork : IUnitOfWork
    {
        private readonly InsuranceApiContext _insuranceApiContext;
        private IGenericRepository<Surcharge> _surcharges;

        public UnitOfWork(InsuranceApiContext insuranceApiContext)
        {
            _insuranceApiContext = insuranceApiContext;
        }

        public IGenericRepository<Surcharge> Surcharges => _surcharges ??= new GenericRepository<Surcharge>(_insuranceApiContext);

        public void Dispose()
        {
            _insuranceApiContext.Dispose();
            GC.SuppressFinalize(this);
        }

        public async Task Save()
        {
            await _insuranceApiContext.SaveChangesAsync();
        }
    }
}