Exemple #1
0
        public override TDbContext Create()
        {
            var dbContextMock = new Mock <TDbContext>(ConstructorParameters.ToArray());

            dbContextMock.DefaultValueProvider = new NoSetUpDefaultValueProvider <TDbContext>(DbContext);

            dbContextMock.Setup(m => m.Add(It.IsAny <object>())).Returns((object providedEntity) => DbContext.Add(providedEntity));
            dbContextMock.Setup(m => m.AddAsync(It.IsAny <object>(), It.IsAny <CancellationToken>()))
            .Returns((object providedEntity, CancellationToken providedCancellationToken) => DbContext.AddAsync(providedEntity, providedCancellationToken));
            dbContextMock.Setup(m => m.AddRange(It.IsAny <object[]>())).Callback((object[] providedEntities) => DbContext.AddRange(providedEntities));
            dbContextMock.Setup(m => m.AddRange(It.IsAny <IEnumerable <object> >())).Callback((IEnumerable <object> providedEntities) => DbContext.AddRange(providedEntities));
            dbContextMock.Setup(m => m.AddRangeAsync(It.IsAny <object[]>(), It.IsAny <CancellationToken>()))
            .Returns((object[] providedEntities, CancellationToken providedCancellationToken) => DbContext.AddRangeAsync(providedEntities, providedCancellationToken));
            dbContextMock.Setup(m => m.AddRangeAsync(It.IsAny <IEnumerable <object> >(), It.IsAny <CancellationToken>()))
            .Returns((IEnumerable <object> providedEntities, CancellationToken providedCancellationToken) =>
                     DbContext.AddRangeAsync(providedEntities, providedCancellationToken));

            dbContextMock.Setup(m => m.Attach(It.IsAny <object>())).Returns((object providedEntity) => DbContext.Attach(providedEntity));
            dbContextMock.Setup(m => m.AttachRange(It.IsAny <object[]>())).Callback((object[] providedEntities) => DbContext.AttachRange(providedEntities));
            dbContextMock.Setup(m => m.AttachRange(It.IsAny <IEnumerable <object> >())).Callback((IEnumerable <object> providedEntities) => DbContext.AttachRange(providedEntities));

            dbContextMock.As <IDbContextDependencies>().Setup(m => m.ChangeDetector).Returns(((IDbContextDependencies)DbContext).ChangeDetector);
            dbContextMock.Setup(m => m.ChangeTracker).Returns(() => DbContext.ChangeTracker);
            dbContextMock.Setup(m => m.ContextId).Returns(() => DbContext.ContextId);
            dbContextMock.Setup(m => m.Database).Returns(() => DbContext.Database);
            dbContextMock.Setup(m => m.Dispose()).Callback(() => DbContext.Dispose());
            dbContextMock.Setup(m => m.DisposeAsync()).Callback(() => DbContext.DisposeAsync());
            dbContextMock.As <IDbContextDependencies>().Setup(m => m.EntityFinderFactory).Returns(((IDbContextDependencies)DbContext).EntityFinderFactory);
            dbContextMock.As <IDbContextDependencies>().Setup(m => m.EntityGraphAttacher).Returns(((IDbContextDependencies)DbContext).EntityGraphAttacher);
            dbContextMock.Setup(m => m.Entry(It.IsAny <object>())).Returns((object providedEntity) => DbContext.Entry(providedEntity));

            dbContextMock.Setup(m => m.Find(It.IsAny <Type>(), It.IsAny <object[]>()))
            .Returns((Type providedEntityType, object[] providedKeyValues) => DbContext.Find(providedEntityType, providedKeyValues));
            dbContextMock.Setup(m => m.FindAsync(It.IsAny <Type>(), It.IsAny <object[]>()))
            .Returns((Type providedEntityType, object[] providedKeyValues) => DbContext.FindAsync(providedEntityType, providedKeyValues));
            dbContextMock.Setup(m => m.FindAsync(It.IsAny <Type>(), It.IsAny <object[]>(), It.IsAny <CancellationToken>()))
            .Returns((Type providedEntityType, object[] providedKeyValues, CancellationToken providedCancellationToken) =>
                     DbContext.FindAsync(providedEntityType, providedKeyValues, providedCancellationToken));

            dbContextMock.As <IDbSetCache>()
            .Setup(m => m.GetOrAddSet(It.IsAny <IDbSetSource>(), It.IsAny <Type>()))
            .Returns((IDbSetSource providedSource, Type providedType) => ((IDbSetCache)DbContext).GetOrAddSet(providedSource, providedType));
            dbContextMock.As <IDbContextDependencies>().Setup(m => m.InfrastructureLogger).Returns(((IDbContextDependencies)DbContext).InfrastructureLogger);
            dbContextMock.As <IInfrastructure <IServiceProvider> >().Setup(m => m.Instance).Returns(((IInfrastructure <IServiceProvider>)DbContext).Instance);
            //dbContextMock.As<IDbContextDependencies>().Setup(m => m.Model).Returns(((IDbContextDependencies) DbContext).Model);
            dbContextMock.As <IDbContextDependencies>().Setup(m => m.QueryProvider).Returns(((IDbContextDependencies)DbContext).QueryProvider);

            dbContextMock.Setup(m => m.Remove(It.IsAny <object>())).Returns((object providedEntity) => DbContext.Remove(providedEntity));
            dbContextMock.Setup(m => m.RemoveRange(It.IsAny <IEnumerable <object> >())).Callback((IEnumerable <object> providedEntities) => DbContext.RemoveRange(providedEntities));
            dbContextMock.Setup(m => m.RemoveRange(It.IsAny <object[]>())).Callback((object[] providedEntities) => DbContext.RemoveRange(providedEntities));

            dbContextMock.As <IDbContextPoolable>().Setup(m => m.ResetState()).Callback(((IDbContextPoolable)DbContext).ResetState);
            dbContextMock.As <IDbContextPoolable>()
            .Setup(m => m.ResetStateAsync(It.IsAny <CancellationToken>()))
            .Callback((CancellationToken providedCancellationToken) => ((IDbContextPoolable)DbContext).ResetStateAsync(providedCancellationToken));
            // dbContextMock.As<IDbContextPoolable>()
            //     .Setup(m => m.Resurrect(It.IsAny<DbContextPoolConfigurationSnapshot>()))
            //     .Callback((DbContextPoolConfigurationSnapshot providedConfigurationSnapshot) => ((IDbContextPoolable) DbContext).Resurrect(providedConfigurationSnapshot));

            dbContextMock.Setup(m => m.SaveChanges()).Returns(() => DbContext.SaveChanges());
            dbContextMock.Setup(m => m.SaveChanges(It.IsAny <bool>())).Returns((bool providedAcceptAllChangesOnSuccess) => DbContext.SaveChanges(providedAcceptAllChangesOnSuccess));
            dbContextMock.Setup(m => m.SaveChangesAsync(It.IsAny <CancellationToken>()))
            .Returns((CancellationToken providedCancellationToken) => DbContext.SaveChangesAsync(providedCancellationToken));
            dbContextMock.Setup(m => m.SaveChangesAsync(It.IsAny <bool>(), It.IsAny <CancellationToken>()))
            .Returns((bool providedAcceptAllChangesOnSuccess, CancellationToken providedCancellationToken) =>
                     DbContext.SaveChangesAsync(providedAcceptAllChangesOnSuccess, providedCancellationToken));

            // dbContextMock.As<IDbContextPoolable>()
            //     .Setup(m => m.SetPool(It.IsAny<IDbContextPool>()))
            //     .Callback((IDbContextPool providedContextPool) => ((IDbContextPoolable) DbContext).SetPool(providedContextPool));
            dbContextMock.As <IDbContextDependencies>().Setup(m => m.SetSource).Returns(((IDbContextDependencies)DbContext).SetSource);
            // dbContextMock.As<IDbContextPoolable>().Setup(m => m.SnapshotConfiguration()).Returns(((IDbContextPoolable) DbContext).SnapshotConfiguration());
            dbContextMock.As <IDbContextDependencies>().Setup(m => m.StateManager).Returns(((IDbContextDependencies)DbContext).StateManager);

            dbContextMock.Setup(m => m.Update(It.IsAny <object>())).Returns((object providedEntity) => DbContext.Update(providedEntity));

            dbContextMock.As <IDbContextDependencies>().Setup(m => m.UpdateLogger).Returns(((IDbContextDependencies)DbContext).UpdateLogger);

            dbContextMock.Setup(m => m.UpdateRange(It.IsAny <IEnumerable <object> >())).Callback((IEnumerable <object> providedEntities) => DbContext.UpdateRange(providedEntities));
            dbContextMock.Setup(m => m.UpdateRange(It.IsAny <object[]>())).Callback((object[] providedEntities) => DbContext.UpdateRange(providedEntities));

            //Relational set up
            var rawSqlCommandBuilderMock = new Mock <IRawSqlCommandBuilder>();

            rawSqlCommandBuilderMock.Setup(m => m.Build(It.IsAny <string>(), It.IsAny <IEnumerable <object> >()))
            .Callback((string providedSql, IEnumerable <object> providedParameters) => Logger.LogDebug("Catch all exception invoked"))
            .Throws <InvalidOperationException>();
            var rawSqlCommandBuilder = rawSqlCommandBuilderMock.Object;

            // var concurrencyDetectorMock = new Mock<IConcurrencyDetector>();
            // concurrencyDetectorMock.Setup(x => x.EnterCriticalSection()).Returns(() => new ConcurrencyDetectorCriticalSectionDisposer(Mock.Of<IConcurrencyDetector>()));
            // var concurrencyDetector = concurrencyDetectorMock.Object;

            var relationalConnectionMock = new Mock <IRelationalConnection>();

            relationalConnectionMock.Setup(x => x.CommandTimeout).Returns(() => 0);
            var relationalConnection = relationalConnectionMock.Object;

            var dependenciesMock = new Mock <IRelationalDatabaseFacadeDependencies>();

            //dependenciesMock.Setup(m => m.ConcurrencyDetector).Returns(() => concurrencyDetector);
            dependenciesMock.Setup(m => m.CommandLogger).Returns(() => Mock.Of <IRelationalCommandDiagnosticsLogger>());
            dependenciesMock.Setup(m => m.RawSqlCommandBuilder).Returns(() => rawSqlCommandBuilder);
            dependenciesMock.Setup(m => m.RelationalConnection).Returns(() => relationalConnection);
            //dependenciesMock.Setup(m => m.CoreOptions.IsConcurrencyDetectionEnabled).Returns(() => true);
            dependenciesMock.Setup(m => m.CoreOptions.AreThreadSafetyChecksEnabled).Returns(() => false);
            var dependencies = dependenciesMock.Object;

            var serviceProviderMock = new Mock <IServiceProvider>();

            serviceProviderMock.Setup(m => m.GetService(It.Is <Type>(t => t == typeof(IDatabaseFacadeDependencies)))).Returns((Type providedType) => dependencies);
            var serviceProvider = serviceProviderMock.Object;

            dbContextMock.As <IInfrastructure <IServiceProvider> >().Setup(m => m.Instance).Returns(() => serviceProvider);

            var mockedDbContext = dbContextMock.Object;

            var databaseFacadeMock = new Mock <DatabaseFacade>(mockedDbContext);

            databaseFacadeMock.As <IDatabaseFacadeDependenciesAccessor>().Setup(x => x.Dependencies).Returns(() => dependencies);
            databaseFacadeMock.Setup(x => x.BeginTransaction()).Returns(() => Mock.Of <IDbContextTransaction>());
            var databaseFacade = databaseFacadeMock.Object;

            dbContextMock.Setup(m => m.Database).Returns(() => databaseFacade);

            return(mockedDbContext);
        }
Exemple #2
0
        public override TDbContext Create()
        {
            var mockedDbContext = (TDbContext)Substitute.For(new[] {
                typeof(TDbContext), typeof(IDbContextDependencies), typeof(IDbSetCache), typeof(IInfrastructure <IServiceProvider>), typeof(IDbContextPoolable)
            },
                                                             ConstructorParameters.ToArray());

            var router = SubstitutionContext.Current.GetCallRouterFor(mockedDbContext);

            router.RegisterCustomCallHandlerFactory(state => new NoSetUpHandler());

            mockedDbContext.Add(Arg.Any <object>()).Returns(callInfo => DbContext.Add(callInfo.Arg <object>()));
            mockedDbContext.AddAsync(Arg.Any <object>(), Arg.Any <CancellationToken>())
            .Returns(callInfo => DbContext.AddAsync(callInfo.Arg <object>(), callInfo.Arg <CancellationToken>()));
            mockedDbContext.When(x => x.AddRange(Arg.Any <object[]>())).Do(callInfo => DbContext.AddRange(callInfo.Arg <object[]>()));
            mockedDbContext.When(x => x.AddRange(Arg.Any <IEnumerable <object> >())).Do(callInfo => DbContext.AddRange(callInfo.Arg <IEnumerable <object> >()));
            mockedDbContext.AddRangeAsync(Arg.Any <object[]>(), Arg.Any <CancellationToken>())
            .Returns(callInfo => DbContext.AddRangeAsync(callInfo.Arg <object[]>(), callInfo.Arg <CancellationToken>()));
            mockedDbContext.AddRangeAsync(Arg.Any <IEnumerable <object> >(), Arg.Any <CancellationToken>())
            .Returns(callInfo => DbContext.AddRangeAsync(callInfo.Arg <object>(), callInfo.Arg <CancellationToken>()));

            mockedDbContext.Attach(Arg.Any <object>()).Returns(callInfo => DbContext.Attach(callInfo.Arg <object>()));
            mockedDbContext.When(x => x.AttachRange(Arg.Any <object[]>())).Do(callInfo => DbContext.AttachRange(callInfo.Arg <object[]>()));
            mockedDbContext.When(x => x.AttachRange(Arg.Any <IEnumerable <object> >())).Do(callInfo => DbContext.AttachRange(callInfo.Arg <IEnumerable <object> >()));

            ((IDbContextDependencies)mockedDbContext).ChangeDetector.Returns(callInfo => ((IDbContextDependencies)DbContext).ChangeDetector);
            mockedDbContext.ChangeTracker.Returns(callInfo => DbContext.ChangeTracker);
            mockedDbContext.ContextId.Returns(callInfo => DbContext.ContextId);
            mockedDbContext.Database.Returns(callInfo => DbContext.Database);
            mockedDbContext.When(x => x.Dispose()).Do(callInfo => DbContext.Dispose());
            mockedDbContext.DisposeAsync().Returns(callInfo => DbContext.DisposeAsync());
            ((IDbContextDependencies)mockedDbContext).EntityFinderFactory.Returns(callInfo => ((IDbContextDependencies)DbContext).EntityFinderFactory);
            ((IDbContextDependencies)mockedDbContext).EntityGraphAttacher.Returns(callInfo => ((IDbContextDependencies)DbContext).EntityGraphAttacher);
            mockedDbContext.Entry(Arg.Any <object>()).Returns(callInfo => DbContext.Entry(callInfo.Arg <object>()));

            mockedDbContext.Find(Arg.Any <Type>(), Arg.Any <object[]>()).Returns(callInfo => DbContext.Find(callInfo.Arg <Type>(), callInfo.Arg <object[]>()));
            mockedDbContext.FindAsync(Arg.Any <Type>(), Arg.Any <object[]>()).Returns(callInfo => DbContext.FindAsync(callInfo.Arg <Type>(), callInfo.Arg <object[]>()));
            mockedDbContext.FindAsync(Arg.Any <Type>(), Arg.Any <object[]>(), Arg.Any <CancellationToken>())
            .Returns(callInfo => DbContext.FindAsync(callInfo.Arg <Type>(), callInfo.Arg <object[]>(), callInfo.Arg <CancellationToken>()));

            ((IDbSetCache)mockedDbContext).GetOrAddSet(Arg.Any <IDbSetSource>(), Arg.Any <Type>())
            .Returns(callInfo => ((IDbSetCache)DbContext).GetOrAddSet(callInfo.Arg <IDbSetSource>(), callInfo.Arg <Type>()));
            ((IDbContextDependencies)mockedDbContext).InfrastructureLogger.Returns(callInfo => ((IDbContextDependencies)DbContext).InfrastructureLogger);
            ((IInfrastructure <IServiceProvider>)mockedDbContext).Instance.Returns(callInfo => ((IInfrastructure <IServiceProvider>)DbContext).Instance);
            ((IDbContextDependencies)mockedDbContext).Model.Returns(callInfo => ((IDbContextDependencies)DbContext).Model);
            ((IDbContextDependencies)mockedDbContext).QueryProvider.Returns(callInfo => ((IDbContextDependencies)DbContext).QueryProvider);

            mockedDbContext.Remove(Arg.Any <object>()).Returns(callInfo => DbContext.Remove(callInfo.Arg <object>()));
            mockedDbContext.When(x => x.RemoveRange(Arg.Any <object[]>())).Do(callInfo => DbContext.RemoveRange(callInfo.Arg <object[]>()));
            mockedDbContext.When(x => x.RemoveRange(Arg.Any <IEnumerable <object> >())).Do(callInfo => DbContext.RemoveRange(callInfo.Arg <IEnumerable <object> >()));

            ((IDbContextPoolable)mockedDbContext).When(x => x.ResetState()).Do(callInfo => ((IDbContextPoolable)DbContext).ResetState());
            ((IDbContextPoolable)mockedDbContext).When(x => x.ResetStateAsync(Arg.Any <CancellationToken>()))
            .Do(callInfo => ((IDbContextPoolable)DbContext).ResetStateAsync(callInfo.Arg <CancellationToken>()));
            // ((IDbContextPoolable) mockedDbContext).When(x => x.Resurrect(Arg.Any<DbContextPoolConfigurationSnapshot>()))
            //     .Do(callInfo => ((IDbContextPoolable) DbContext).Resurrect(callInfo.Arg<DbContextPoolConfigurationSnapshot>()));

            mockedDbContext.SaveChanges().Returns(callInfo => DbContext.SaveChanges());
            mockedDbContext.SaveChanges(Arg.Any <bool>()).Returns(callInfo => DbContext.SaveChanges(callInfo.Arg <bool>()));
            mockedDbContext.SaveChangesAsync(Arg.Any <CancellationToken>()).Returns(callInfo => DbContext.SaveChangesAsync(callInfo.Arg <CancellationToken>()));
            mockedDbContext.SaveChangesAsync(Arg.Any <bool>(), Arg.Any <CancellationToken>())
            .Returns(callInfo => DbContext.SaveChangesAsync(callInfo.Arg <bool>(), callInfo.Arg <CancellationToken>()));

            // ((IDbContextPoolable) mockedDbContext).When(x => x.SetPool(Arg.Any<IDbContextPool>()))
            //     .Do(callInfo => ((IDbContextPoolable) DbContext).SetPool(callInfo.Arg<IDbContextPool>()));
            ((IDbContextDependencies)mockedDbContext).SetSource.Returns(callInfo => ((IDbContextDependencies)DbContext).SetSource);
            // ((IDbContextPoolable) mockedDbContext).SnapshotConfiguration().Returns(callInfo => ((IDbContextPoolable) DbContext).SnapshotConfiguration());
            ((IDbContextDependencies)mockedDbContext).StateManager.Returns(callInfo => ((IDbContextDependencies)DbContext).StateManager);

            mockedDbContext.Update(Arg.Any <object>()).Returns(callInfo => DbContext.Update(callInfo.Arg <object>()));

            ((IDbContextDependencies)mockedDbContext).UpdateLogger.Returns(callInfo => ((IDbContextDependencies)DbContext).UpdateLogger);

            mockedDbContext.When(x => x.UpdateRange(Arg.Any <object[]>())).Do(callInfo => DbContext.UpdateRange(callInfo.Arg <object[]>()));
            mockedDbContext.When(x => x.UpdateRange(Arg.Any <IEnumerable <object> >())).Do(callInfo => DbContext.UpdateRange(callInfo.Arg <IEnumerable <object> >()));

            foreach (var entity in DbContext.Model.GetEntityTypes().Where(x => x.FindPrimaryKey() != null))
            {
                typeof(MockedDbContextFactory <TDbContext>).GetMethod(nameof(SetUpModelEntity), BindingFlags.Instance | BindingFlags.NonPublic)
                .MakeGenericMethod(entity.ClrType)
                .Invoke(this, new object[] { mockedDbContext });
            }

            foreach (var entity in DbContext.Model.GetEntityTypes().Where(x => x.FindPrimaryKey() == null))
            {
                typeof(MockedDbContextFactory <TDbContext>).GetMethod(nameof(SetUpReadOnlyModelEntity), BindingFlags.Instance | BindingFlags.NonPublic)
                .MakeGenericMethod(entity.ClrType)
                .Invoke(this, new object[] { mockedDbContext });
            }

            //Relational set up
            var rawSqlCommandBuilder = Substitute.For <IRawSqlCommandBuilder>();

            rawSqlCommandBuilder.Build(Arg.Any <string>(), Arg.Any <IEnumerable <object> >())
            .Throws(callInfo =>
            {
                Logger.LogDebug("Catch all exception invoked");
                return(new InvalidOperationException());
            });

            var concurrencyDetector = Substitute.For <IConcurrencyDetector>();

            concurrencyDetector.EnterCriticalSection().Returns(callInfo => new ConcurrencyDetectorCriticalSectionDisposer(Substitute.For <IConcurrencyDetector>()));

            var relationalConnection = Substitute.For <IRelationalConnection>();

            relationalConnection.CommandTimeout.Returns(callInfo => 0);

            var dependencies = Substitute.For <IRelationalDatabaseFacadeDependencies>();

            dependencies.ConcurrencyDetector.Returns(callInfo => concurrencyDetector);
            dependencies.CommandLogger.Returns(callInfo => Substitute.For <IDiagnosticsLogger <DbLoggerCategory.Database.Command> >());
            dependencies.RawSqlCommandBuilder.Returns(callInfo => rawSqlCommandBuilder);
            dependencies.RelationalConnection.Returns(callInfo => relationalConnection);

            var serviceProvider = Substitute.For <IServiceProvider>();

            serviceProvider.GetService(Arg.Is <Type>(t => t == typeof(IDatabaseFacadeDependencies))).Returns(callInfo => dependencies);

            ((IInfrastructure <IServiceProvider>)mockedDbContext).Instance.Returns(callInfo => serviceProvider);

            var databaseFacade = Substitute.For(new[] { typeof(DatabaseFacade), typeof(IDatabaseFacadeDependenciesAccessor) }, new[] { mockedDbContext });

            ((IDatabaseFacadeDependenciesAccessor)databaseFacade).Dependencies.Returns(callInfo => dependencies);

            mockedDbContext.Database.Returns(callInfo => databaseFacade);

            return(mockedDbContext);
        }