【问题标题】:unit test for MediatR in .net6 with generic repo returns null repository具有通用存储库的 .net6 中 MediatR 的单元测试返回空存储库
【发布时间】:2022-01-08 10:14:00
【问题描述】:

我正在使用 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,当我运行测试时,存储库对象为空。

这是我的存储库界面和 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());

  
}

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

【问题讨论】:

    标签: unit-testing .net-core mocking moq mediatr


    【解决方案1】:

    我应该将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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-29
      • 1970-01-01
      • 1970-01-01
      • 2019-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多