使用通用存储库 returns 空存储库对 .net6 中的 MediatR 进行单元测试

unit test for MediatR in .net6 with generic repo returns null repository

我正在使用 MediatR 进行命令查询隔离。 我想测试命令方法,我的命令方法接受一个 clientappsetting 模型作为输入。在这里你可以看到我的整个处理程序和命令代码:

   AddClientAppSettingCommandHandler : IRequestHandler<AddClientAppSettingCommand, AddClientAppSettingResponse>
    {
        private readonly ICurrentUserService _userService;
        private readonly IRepository<ClientAppSettings> _repository;

        public AddClientAppSettingCommandHandler(ICurrentUserService userService,
            IRepositoryAccessor repositoryAccessor)
        {
            _userService = userService;
            _repository = repositoryAccessor.GetRepository<ClientAppSettings>(_userService.CustomerIsin,
                reThrowException: true, type: DatabaseType.Raven);
        }

        public async Task<AddClientAppSettingResponse> Handle(AddClientAppSettingCommand request,
            CancellationToken cancellationToken)
        {
            var entity = new ClientAppSettings(_userService.CustomerIsin)
            {
                LightTheme = request.Setting.LightTheme,
                Order = request.Setting.Order,
                Notch = request.Setting.Notch,
                PageSize = request.Setting.PageSize,
                ApplyCommissionInPortfolio = request.Setting.ApplyCommissionInPortfolio,
                UseClosingPriceInPortfolioTotalValue = request.Setting.UseClosingPriceInPortfolioTotalValue,
                ShowNotifications = request.Setting.ShowNotifications,
                NoSleep = request.Setting.NoSleep,
                NoBalance = request.Setting.NoBalance,
                DataTracker = request.Setting.DataTracker,
                UserStatusBarToUp = request.Setting.UserStatusBarToUp,
                PortfolioBasedOnLastPositivePeriod = request.Setting.PortfolioBasedOnLastPositivePeriod,
            };
            var cRepository = CacheableRepository<ClientAppSettings>.From(_repository);
            var result = await cRepository.AddOrUpdateAsync(entity);

            if (!result.IsSucceeded)
                throw new EasyException(EasyException.DATABASE_EXCEPTION, result.Error);
            return AddClientAppSettingResponse.Map(entity);
        }

如您所见,我的处理程序有两个依赖项ICurrentUserService , IRepositoryAccessor

我的问题是 IRepositoryAccessor 当我 运行 测试存储库对象为 null 时。

这是我的存储库界面和 imp ;

public interface IRepositoryAccessor
{
    IRepository<TEntity> GetRepository<TEntity>(
        string shard = "public",
        DatabaseType type = DatabaseType.Raven,
        Type inheritedRepository = null,
        bool manualDisposing = false,
        bool reThrowException=false) where TEntity : BaseEntity;

    void CloseSession();

}

小鬼 :

 public sealed class RepositoryAccessor : IRepositoryAccessor, IDisposable
    {
        private static readonly Dictionary<Type, object> FlyweightSqlGenerator = new();
        private readonly List<IDisposable> _sessions = new();

        private readonly ITracer _tracer;
        private readonly IConfiguration _configuration;
        public RepositoryAccessor(IConfiguration configuration, ITracer tracer = null)
        {
            _configuration = configuration;
            _tracer = tracer;
        }

        public void CloseSession()
        {
            for (int i = 0; i < _sessions.Count; i++)
            {
                _sessions[i].Dispose();
            }
            _sessions.Clear();
        }

        public void Dispose() => CloseSession();


        public IRepository<TEntity> GetRepository<TEntity>(
            string shard = "public",
            DatabaseType type = DatabaseType.Raven,
            Type inheritedRepository = null,
            bool manualDisposing = false,
            bool reThrowException = false) where TEntity : BaseEntity
        {
            if (type == DatabaseType.Raven)
            {
                return GetRavenRepository<TEntity>(inheritedRepository, shard, manualDisposing, reThrowException);
            }
            else if (type == DatabaseType.Redis)
            {
                return new RedisRepository<TEntity>();
            }
            return GetSQLRepository<TEntity>(inheritedRepository, manualDisposing, reThrowException);
        }
}

这是我的测试:

[Fact]
public async void Test1()
{
    //Arange
    var mediator = new Mock<IMediator>();
    var userservice = new Mock<ICurrentUserService>();
    var repo = new Mock<IRepositoryAccessor>();



    AddClientAppSettingCommand command = new AddClientAppSettingCommand(new domain.Entities.ClientAppSettings());
    AddClientAppSettingCommandHandler handler = new AddClientAppSettingCommandHandler(userservice.Object,repo.Object);

    //Act
    var x = await handler.Handle(command, new System.Threading.CancellationToken());

  
}

当我 运行 使用调试模式进行测试时,我的存储库为空:

我应该将 IAccessorIRepository 定义为模拟并为 IAccessor 设置 Irepository,如您所见:

var repoacc = new Mock<IRepositoryAccessor>();
            var repo = new Mock<domain.Interfaces.IRepository<ClientAppSettings>>();

            repoacc.Setup(i => i.GetRepository<ClientAppSettings>(It.IsAny<string>(), DatabaseType.Raven, null, false, true)).Returns(repo.Object);