Search code examples
.net-coremockingmoqxunit.net-6.0

xunit System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')'


Hi I have this test plan as you can see :

[Fact]
        public async void Test1()
        {
            //Arange
            var data = new domain.Entities.ClientAppSettings() { ApplyCommissionInPortfolio = true, CreateDateTime  =System.DateTime.Now, DataTracker=false,
                LightTheme=false, NoBalance=false, NoSleep=false
            , Order=new OrderSettings() { BuyQuantity=1, DivideOrderToMultiple=false, OrderConfirmation=false, SellQuantity=12, PriceFromHeadline=false,
                Tick=121, TickType="" }, Notch=new NotchSettings() { Down=false,Up=true },PageSize=12,PortfolioBasedOnLastPositivePeriod=false,ShowNotifications=false,
                UseClosingPriceInPortfolioTotalValue=false,UserStatusBarToUp    =false
           };
            var mediator = new Mock<IMediator>();
            var userservice = new Mock<ICurrentUserService>();


            var isession = new Mock<IAsyncDocumentSession>();
            var itracer = new Mock<ITracer>();
            var ravenRepo = new RavenRepository<ClientAppSettings>(isession.Object,itracer.Object,true);
           


            var repoacc = new Mock<IRepositoryAccessor>();
            var repo = new Mock<domain.Interfaces.IRepository<ClientAppSettings>>();
            repo.Setup(i=>It.IsAny<IRepository<ClientAppSettings>>()).Returns(ravenRepo);

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

            AddClientAppSettingCommand command = new AddClientAppSettingCommand(data);
            AddClientAppSettingCommandHandler handler = new AddClientAppSettingCommandHandler(userservice.Object, repoacc.Object);

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

            //Asert
            //Do the assertion

            //something like:
            //mediator.Verify(x => x.Publish(It.IsAny<CustomersChanged>()));
        }

But in this line

    repo.Setup(i=>It.IsAny<IRepository<ClientAppSettings>>()).Returns(ravenRepo);

I get this error:

        repo.Setup(i=>It.IsAny<IRepository<ClientAppSettings>>()).Returns(ravenRepo);

enter image description here


Solution

  •    repo.Setup(i=>It.IsAny<IRepository<ClientAppSettings>>()).Returns(ravenRepo);
    

    The expression above is wrong, you are not providing the method you are setting up here.

    The correct version should look similar to this:

    repo.Setup(i => i.AddOrUpdateAsync(It.IsAny<ClientAppSettings>())).Returns(Task.FromResult(OperationResult.Succeed()));
    

    Alternatively you can use the ReturnsAsync method as well:

    repo.Setup(i => i.AddOrUpdateAsync(It.IsAny<ClientAppSettings>())).ReturnsAsync(OperationResult.Succeed());