/// <summary> /// Setup mock /// </summary> /// <param name="mock"></param> private static void Setup(AutoMock mock) { mock.Provide <IDatabaseServer, MemoryDatabase>(); mock.Provide <IItemContainerFactory, ItemContainerFactory>(); mock.Provide <IKeyStore, KeyDatabase>(); mock.Provide <IKeyHandleSerializer, KeyHandleSerializer>(); mock.Provide <ICertificateFactory, CertificateFactory>(); }
private static CalendarService CreateServiceForEventFromSeries(AutoMock mock) { mock.Provide <IEventSeriesRepository, CalendarRepository>(); mock.Provide <IEventSeriesService, CalendarService>(); mock.Provide <IEventFromSeriesRepository, CalendarRepository>(); mock.Provide <IEventFromSeriesService, CalendarService>(); return(mock.Create <CalendarService>()); }
/// <summary> /// Setup all services used in processing /// </summary> /// <param name="mock"></param> /// <param name="registry"></param> private static IDiscoveryProcessor Setup(AutoMock mock, IoTHubServices registry) { mock.Provide <IIoTHubTwinServices>(registry); mock.Provide <IApplicationRepository, ApplicationTwins>(); mock.Provide <ISupervisorRegistry, SupervisorRegistry>(); mock.Provide <IEndpointBulkProcessor, EndpointRegistry>(); mock.Provide <IApplicationBulkProcessor, ApplicationRegistry>(); return(mock.Create <DiscoveryProcessor>()); }
public void SetUp() { mocker = AutoMock.GetLoose(); mocker.Provide <ICalculatePeriodStartAndEndDate, CalculatePeriodStartAndEndDate>(); mocker.Provide <IFunctionalSkillValidationProcessor>(new FunctionalSkillValidationProcessor(new List <ICourseValidator> { new ApprenticeshipPauseValidator() })); }
private void CreateMock(AutoMock mock) { var defaults = new DefaultsFactory(); var mockSQLiteRepository = new MockSQLiteRepository(defaults); mock.Provide <ISQLiteRepository>(mockSQLiteRepository); // using the real settings factory because it's just a POCO var realSettingsFactory = new SettingsFactory(defaults); mock.Provide <ISettingsFactory>(realSettingsFactory); }
public void SetUp() { mocker = AutoMock.GetLoose(); mocker.Provide <IStartDateValidator>(new StartDateValidator(false)); mocker.Provide <ICalculatePeriodStartAndEndDate, CalculatePeriodStartAndEndDate>(); mocker.Provide <IOnProgrammeAndIncentiveStoppedValidator, OnProgrammeAndIncentiveStoppedValidator>(); mocker.Provide <ICompletionStoppedValidator, CompletionStoppedValidator>(); mocker.Provide <ICourseValidationProcessor>(new CourseValidationProcessor(new List <ICourseValidator> { new StandardCodeValidator(), new ProgrammeTypeValidator() })); }
public async Task Calculates_RequiredPaymentsDasEarningsComparison_Correctly() { moqer.Provide <ISubmissionSummaryFactory>(new SubmissionSummaryFactory()); var service = moqer.Create <SubmissionMetricsService>(); await service.BuildMetrics(1234, 123, 1920, 1, CancellationToken.None).ConfigureAwait(false); moqer.Mock <ITelemetry>() .Verify(t => t.TrackEvent( It.Is <string>(s => s == "Finished Generating Submission Metrics"), It.IsAny <Dictionary <string, string> >(), It.Is <Dictionary <string, double> >(dictionary => dictionary.Contains(new KeyValuePair <string, double>("RequiredPaymentsDasEarningsPercentageComparison", 90.8))))); }
public void Initialize() { var container = Container.Get(); _mock = AutoMock.GetLoose(); _mock.Provide(container.Resolve <INamedInstanceFactory>()); _mock.Provide <ILinqExpressionTransformer <LambdaExpression>, LinqLambdaExpressionTransformer>(); _lambdaExpressionTransformer = _mock.Create <LinqLambdaExpressionTransformer>(); _to = new To { String = "TestString", Number = 10 }; }
public void SetupMockForViewModels(AutoMock mock) { settingsFactory = new SettingsFactory(defaultsFactory); var sqlLiteRepository = new MockSQLiteRepository(defaultsFactory); var settingsService = new SettingsService(sqlLiteRepository, settingsFactory); mock.Provide <ISettingsService>(settingsService); mock.Provide <ISettingsFactory>(settingsFactory); mock.Provide <IDefaultsFactory>(defaultsFactory); // the following will allow autofaq to automatically inject IPlatformStuffService // It will also change the normal operation of GetBaseUrl() // since that single method is the only difficult to test method, no point in creating a // custom mock for the entire service. mock.Mock <IPlatformStuffService>().Setup(x => x.GetBaseUrl()).Returns("some base url"); }
public void Does_Not_Auto_Fake_Enumerable() { AutoMock.Provide <Item>(new A()); AutoMock.Provide <Item>(new B()); AutoMock.Resolve <IEnumerable <Item> >().Should().HaveCount(2); }
public void Setup() { DataStore = new List <Cast>() { new Cast { Id = 1, FirstName = "Action", LastName = "Hello", VideoId = 1, DateCreated = DateTime.Now, IsDeleted = false, TitleId = 1 }, new Cast { Id = 2, FirstName = "Comedy", LastName = "bye", VideoId = 1, DateCreated = DateTime.Now, IsDeleted = false, DateUpdated = DateTime.Now.AddDays(2), TitleId = 1 }, new Cast { Id = 3, FirstName = "Horror", LastName = "Great", VideoId = 1, DateCreated = DateTime.Now, IsDeleted = true, DateUpdated = DateTime.Now.AddDays(2), DateDeleted = DateTime.Now.AddDays(5), TitleId = 1 } }; SetupTitlesMockDbSet(); SetupCastMockDbSet(); MockContext = new Mock <DataStoreContext>(); MockContext.Setup(m => m.Set <Title>()).Returns(MockTitleSet.Object); MockContext.Setup(m => m.Set <Cast>()).Returns(MockCastSet.Object); MockContext.Setup(m => m.SaveChanges()).Returns(1); MockContext.Setup(c => c.Titles).Returns(MockTitleSet.Object); MockContext.Setup(c => c.Casts).Returns(MockCastSet.Object); AutoMock = AutoMock.GetLoose(); AutoMock.Provide(MockContext.Object); AutoMock.Provide <IRepository <Cast, int>, Repository <Cast, int> >(); AutoMock.Provide <IRepository <Title, int>, Repository <Title, int> >(); AutoMock.Provide <IService <Cast, int>, CastService>(); AutoMock.Provide <IService <Title, int>, TitleService>(); AutoMock.Provide <IValidationService <Cast>, CastValidationService>(); AutoMock.Provide <IValidationExceptionService, ValidationExceptionService>(); Controller = AutoMock.Create <CastController>(); }
public FileProcessorTests(AppSettingsFixture appSettingsFixture) { _appSettingsFixture = appSettingsFixture; _mock = AutoMock.GetLoose(); _mock.Provide <IAppSettings>(_appSettingsFixture.AppSettings); _sut = _mock.Create <FileProcessor>(); }
public static AutoMock MockServiceContext(this AutoMock mock) { mock.Provide(new NodeContext("Node0", new NodeId(0, 1), 0, "NodeType1", "TEST.MACHINE")); var serviceContext = new StatefulServiceContext( mock.Container.Resolve <NodeContext>(), mock.Mock <ICodePackageActivationContext>().Object, "ShittyServiceType", new Uri("fabric:/someapp/someservice"), null, Guid.NewGuid(), long.MaxValue); mock.Provide(serviceContext); return(mock); }
public void Setup() { MockRepositorySetup = new MockRepositorySetup <Rental>( new Mock <IRepository <Rental, int> >(), (new List <Rental>() { new Rental { Id = 1, VideoId = 1, StatusId = 1, UserId = "a017433b-ff94-44a7-a519-c5df1c18e7ad", DateCreated = DateTime.Now, IsCheckedOut = true } //new Rental{ Id=1, //VideoId=1, //StatusId=1, //UserId="a017433b-ff94-44a7-a519-c5df1c18e7ad", //DateCreated = DateTime.Now, //IsCheckedOut = true, // DateUpdated = DateTime.Now.AddDays(2)} })).Setup(); AutoMock = AutoMock.GetLoose(); AutoMock.Provide(MockRepositorySetup.MockRepository.Object); AutoMock.Provide <IValidationService <Rental>, RentalValidationService>(); AutoMock.Provide <IValidationExceptionService, ValidationExceptionService>(); RentalService = AutoMock.Create <RentalService>(); }
public void Should_Populate_Optional_Parameters_When_Provided() { AutoMock.Provide<IItem>(new MyItem()); var optional = AutoMock.Resolve<Optional>(); optional.Item.Should().NotBeNull(); Action a = () => Mock.Get(optional); a.Should().Throw<ArgumentException>(); }
public void Handle_One_Fake_Item() { var fake1 = AutoMock.Provide(FakeItEasy.A.Fake <Item>()); var result = AutoMock.Resolve <IEnumerable <Item> >().ToArray(); result.Should().HaveCount(1); result.Should().Contain(fake1); }
public void SetUp() { mocker = AutoMock.GetLoose(); history = new List <PaymentHistoryEntity>(); var config = new MapperConfiguration(cfg => cfg.AddProfile <RequiredPaymentsProfile>()); config.AssertConfigurationIsValid(); var mapper = new Mapper(config); mocker.Provide <IMapper>(mapper); var logger = new Mock <IPaymentLogger>(); duplicateEarningsServiceMock = mocker.Mock <IDuplicateEarningEventService>(); mocker.Provide <IRefundRemovedLearningAimService>(new RefundRemovedLearningAimService()); mocker.Provide <IPeriodisedRequiredPaymentEventFactory>(new PeriodisedRequiredPaymentEventFactory(logger.Object)); identifiedLearner = new IdentifiedRemovedLearningAim { CollectionPeriod = new CollectionPeriod { AcademicYear = 1819, Period = 1 }, EventId = Guid.NewGuid(), EventTime = DateTimeOffset.UtcNow, IlrSubmissionDateTime = DateTime.Now, JobId = 1, Learner = new Learner { ReferenceNumber = "learner-ref-123", }, LearningAim = new LearningAim { FrameworkCode = 3, FundingLineType = "funding line type", PathwayCode = 4, ProgrammeType = 5, Reference = "learning-ref-456", StandardCode = 6 }, Ukprn = 7 }; }
public void Should_Handle_Creating_A_Mock_With_Logger() { Action a = () => { var lt = AutoMock.Resolve <LoggerTest>(); AutoMock.Provide <Item>(lt); }; a.Should().NotThrow(); }
public async Task RefundsCorrectTypesBasedOnHistory() { var historicalCompletionPayment = CreatePaymentHistoryEntity(FundingSourceType.CoInvestedSfa, 1, TransactionType.Completion); historicalCompletionPayment.Amount = 1000; var historicalBalancingPayment = CreatePaymentHistoryEntity(FundingSourceType.CoInvestedSfa, 1, TransactionType.Balancing); historicalBalancingPayment.Amount = 166.66m; var historicalCompletionUplift = CreatePaymentHistoryEntity(FundingSourceType.FullyFundedSfa, 1, TransactionType.Completion16To18FrameworkUplift); historicalCompletionUplift.Amount = 200m; var historicalBalancingUpliftPayment = CreatePaymentHistoryEntity(FundingSourceType.FullyFundedSfa, 1, TransactionType.Balancing16To18FrameworkUplift); historicalBalancingUpliftPayment.Amount = 33.33m; history.Add(historicalCompletionPayment); history.Add(historicalBalancingPayment); history.Add(historicalCompletionUplift); history.Add(historicalBalancingUpliftPayment); mocker.Mock <IDataCache <PaymentHistoryEntity[]> >() .Setup(x => x.TryGet(It.IsAny <string>(), It.IsAny <CancellationToken>())) .ReturnsAsync(new ConditionalValue <PaymentHistoryEntity[]>(true, history.ToArray())); mocker.Provide <IPeriodisedRequiredPaymentEventFactory, PeriodisedRequiredPaymentEventFactory>(); mocker.Provide <IRefundService, RefundService>(); mocker.Provide <IPaymentDueProcessor, PaymentDueProcessor>(); mocker.Provide <IRefundRemovedLearningAimService, RefundRemovedLearningAimService>(); var processor = mocker.Create <RefundRemovedLearningAimProcessor>(); var refunds = await processor.RefundLearningAim(identifiedLearner, mocker.Mock <IDataCache <PaymentHistoryEntity[]> >().Object, CancellationToken.None).ConfigureAwait(false); refunds.Count.Should().Be(4); refunds[0].Should().BeOfType <CalculatedRequiredCoInvestedAmount>(); refunds[0].AmountDue.Should().Be(-1 * historicalCompletionPayment.Amount); refunds[1].Should().BeOfType <CalculatedRequiredCoInvestedAmount>(); refunds[1].AmountDue.Should().Be(-1 * historicalBalancingPayment.Amount); refunds[2].Should().BeOfType <CalculatedRequiredIncentiveAmount>(); refunds[2].AmountDue.Should().Be(-1 * historicalCompletionUplift.Amount); refunds[3].Should().BeOfType <CalculatedRequiredIncentiveAmount>(); refunds[3].AmountDue.Should().Be(-1 * historicalBalancingUpliftPayment.Amount); }
public void It_Should_Throw_If_Called_With_Illegal_Args(string value) { using (AutoMock mock = AutoMock.GetLoose()) { mock.Provide <IOptions <MessageClientOptions> >(new OptionsWrapper <MessageClientOptions>(new MessageClientOptions { Address = "inproc://address" })); var service = mock.Create <MessageClientImpl>(); var ex = Assert.Throws <ArgumentNullException>(() => service.ScheduleDelivery(value)); Assert.Contains("message", ex.Message); } }
public void Prepare() { mocker = AutoMock.GetStrict(); var earningPeriod = new EarningPeriod { Period = 1 }; dataLockValidationModel = new DataLockValidationModel { EarningPeriod = earningPeriod, PriceEpisode = new PriceEpisode(), Apprenticeship = new ApprenticeshipModel { Id = 1, Uln = 100, ApprenticeshipPriceEpisodes = new List <ApprenticeshipPriceEpisodeModel> { new ApprenticeshipPriceEpisodeModel { Id = 99, ApprenticeshipId = 1, Cost = 100, StartDate = DateTime.Today } } } }; mocker.Mock <IOnProgrammeAndIncentiveStoppedValidator>() .Setup(validator => validator.Validate(It.IsAny <DataLockValidationModel>())) .Returns(() => new ValidationResult()); mocker.Mock <ICompletionStoppedValidator>() .Setup(validator => validator.Validate(It.IsAny <DataLockValidationModel>())) .Returns(() => new ValidationResult()); mocker.Mock <IStartDateValidator>() .Setup(validator => validator.Validate(It.IsAny <DataLockValidationModel>())) .Returns(() => new ValidationResult()) .Verifiable(); negotiatedPriceValidator = new Mock <ICourseValidator>(); apprenticeshipPauseValidator = new Mock <ICourseValidator>(); courseValidators = new List <ICourseValidator> { negotiatedPriceValidator.Object, apprenticeshipPauseValidator.Object, }; mocker.Provide <List <ICourseValidator> >(courseValidators); }
/// <summary> /// Configures <see cref="AutoMock"/> with an in memory database (SQLite) and NHibernate, and runs the migrations on it as provided by the <paramref name="mappingConfiguration"/>. /// </summary> /// <param name="autoMock">The <see cref="AutoMock"/> instance to provide with NHibernate session factory.</param> /// <param name="instanceName">The in memory instance name. Use the same instance name if you need to share in process with other test runs.</param> /// <param name="mappingConfiguration">The migration mappings to execute on each new memory instance of the database.</param> public static ISessionFactory UseInMemoryDatabase(this AutoMock autoMock, string instanceName, Action <MappingConfiguration> mappingConfiguration) { ISessionFactory sessionFactory = Fluently.Configure() .Database( SQLiteConfiguration.Standard .ConnectionString(c => c.Is($"Data Source={instanceName ?? DefaultInstanceName};Mode=Memory;Cache=Shared;Version=3;New=True;")) .ShowSql() ) .ExposeConfiguration(c => new SchemaExport(c).Execute(true, true, false)) .Mappings(mappingConfiguration) .BuildSessionFactory(); autoMock.Provide(sessionFactory); return(sessionFactory); }
public async Task Clawback_ME_OnProgramme_And_Balancing_Payments() { // arrange mocker.Provide <IRefundService, RefundService>(); mocker.Provide <IPaymentDueProcessor, PaymentDueProcessor>(); mocker.Provide <IPeriodisedRequiredPaymentEventFactory, PeriodisedRequiredPaymentEventFactory>(); mocker.Provide <IRefundRemovedLearningAimService, RefundRemovedLearningAimService>(); var historicOnProgrammeMEPayment = CreatePaymentHistoryEntity(FundingSourceType.FullyFundedSfa, 2, 1); historicOnProgrammeMEPayment.Amount = 39.25m; historicOnProgrammeMEPayment.TransactionType = (int)TransactionType.OnProgrammeMathsAndEnglish; historicOnProgrammeMEPayment.PriceEpisodeIdentifier = null; history.Add(historicOnProgrammeMEPayment); var historicBalancingMEPayment = CreatePaymentHistoryEntity(FundingSourceType.FullyFundedSfa, 2, 2); historicBalancingMEPayment.Amount = 39.25m; historicBalancingMEPayment.TransactionType = (int)TransactionType.BalancingMathsAndEnglish; historicBalancingMEPayment.PriceEpisodeIdentifier = null; history.Add(historicBalancingMEPayment); var mockPaymentHistoryCache = mocker.Mock <IDataCache <PaymentHistoryEntity[]> >(); mockPaymentHistoryCache.Setup(x => x.TryGet(It.IsAny <string>(), It.IsAny <CancellationToken>())) .ReturnsAsync(new ConditionalValue <PaymentHistoryEntity[]>(true, history.ToArray())); identifiedLearner.CollectionPeriod.Period = 3; // act var processor = mocker.Create <RefundRemovedLearningAimProcessor>(); var refunds = await processor .RefundLearningAim(identifiedLearner, mockPaymentHistoryCache.Object, CancellationToken.None) .ConfigureAwait(false); // assert using (new AssertionScope()) { refunds.Should().HaveCount(2); refunds.Cast <CalculatedRequiredIncentiveAmount>().Should().ContainSingle(x => x.Type == IncentivePaymentType.BalancingMathsAndEnglish); refunds.Cast <CalculatedRequiredIncentiveAmount>().Should().ContainSingle(x => x.Type == IncentivePaymentType.OnProgrammeMathsAndEnglish); } }
public void SetUp() { mocker = AutoMock.GetLoose(); mocker.Provide <IMapper>(mapper); mocker.Mock <IActorDataCache <List <ApprenticeshipModel> > >() .Setup(x => x.AddOrReplace(It.IsAny <string>(), It.IsAny <List <ApprenticeshipModel> >(), It.IsAny <CancellationToken>())) .Returns(Task.CompletedTask); updatedApprenticeship = new ApprenticeshipUpdated { Id = 123, Ukprn = 123456, Uln = 54321, EmployerAccountId = 1234 }; }
public void Test_Start_Should_Throw_If_Called_Twice() { using (AutoMock mock = AutoMock.GetLoose(this.output.Capture())) { IOptions <MessageHandlerOptions> options = Options.Create(new MessageHandlerOptions { Address = "tcp://127.0.0.1:51861" }); mock.Provide(options); using (var handler = mock.Create <MessageHandlerImpl>()) { handler.Start(); var ex = Assert.Throws <InvalidOperationException>(() => handler.Start()); Assert.Equal("The handler has already been started", ex.Message); } } }
public async Task It_Should_Throw_If_Called_With_Illegal_Args() { using (AutoMock mock = AutoMock.GetLoose()) { IOptions <TelegramOptions> options = Options.Create(new TelegramOptions { Endpoint = new Uri("https://api.telegram.org"), Channel = "abc", Token = "cde" }); mock.Provide(options); var service = mock.Create <TelegramServiceImpl>(); async Task Caller() => await service.SendMessageAsync(null, CancellationToken.None); ArgumentNullException ex = await Assert.ThrowsAsync <ArgumentNullException>(Caller); Assert.Contains("message", ex.Message); } }
public void SetUp() { mocker = AutoMock.GetLoose(); var mapperConfiguration = new MapperConfiguration(expression => { expression.AddProfile(typeof(DataLocksProfile)); }); mocker.Provide <IMapper>(new Mapper(mapperConfiguration)); mocker.Mock <IEndpointInstance>() .Setup(x => x.Publish(It.IsAny <object>(), It.IsAny <PublishOptions>())) .Returns(Task.CompletedTask); mocker.Mock <IEndpointInstanceFactory>() .Setup(x => x.GetEndpointInstance()) .ReturnsAsync(mocker.Mock <IEndpointInstance>().Object); }
/// <summary> /// Configures <see cref="AutoMock"/> so that the <see cref="ISessionFactory"/> returns singleton <see cref="ISession"/> from the mock container, and when a transaction is requested from the session, it returns a singleton <see cref="ITransaction"/>. /// Should only be used if NHibernate in your active test(s) is irrelevant. /// </summary> public static ISessionFactory UseMockedDatabase(this AutoMock autoMock) { Mock <ISession> sessionMock = autoMock.Mock <ISession>(); sessionMock .Setup(m => m.BeginTransaction()) .Returns(autoMock.Mock <ITransaction>().Object); // Create new instance explicitly, instead of via AutoMock. Mock <ISessionFactory> sessionFactoryMock = new Mock <ISessionFactory>(); sessionFactoryMock .Setup(m => m.OpenSession()) .Returns(sessionMock.Object); autoMock.Provide(sessionFactoryMock.Object); return(sessionFactoryMock.Object); }
public void Test_Start_Should_Not_Fail_In_Case_Of_Processing_Exception() { using (AutoMock mock = AutoMock.GetLoose(this.output.Capture())) { IOptions <MessageHandlerOptions> options = Options.Create(new MessageHandlerOptions { Address = "tcp://127.0.0.1:51861" }); mock.Provide(options); mock.Mock <ITelegramService>() .SetupSequence(service => service.SendMessageAsync(It.IsAny <string>(), It.IsAny <CancellationToken>())) .Throws(new Exception("Something threw an exception")) .Returns(Task.CompletedTask); using (var pushSocket = new PushSocket($"@{options.Value.Address}")) using (var handler = mock.Create <MessageHandlerImpl>()) { handler.Start(); pushSocket.SendFrame("some-message1"); pushSocket.SendFrame("some-message2"); Mock <ITelegramService> telegramService = mock.Mock <ITelegramService>(); var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); Predicate <CancellationToken> isNotCancelled = token => !token.IsCancellationRequested; while (!cts.Token.IsCancellationRequested) { try { telegramService.Verify(p => p.SendMessageAsync("some-message1", Match.Create(isNotCancelled)), Times.Once); telegramService.Verify(p => p.SendMessageAsync("some-message2", Match.Create(isNotCancelled)), Times.Once); break; } catch (MockException) { if (cts.Token.IsCancellationRequested) { throw; } } } } } }
public AutoMock GetMock( ) { ImportRun importRun = GetMockRun(MockToken); AutoMock mock = AutoMock.GetStrict(); mock.Provide(importRun); mock.Provide(GetMockFileRepository(MockToken)); mock.Provide(GetMockEntityRepository(MockRunId, importRun)); // OK, that's enough mocking.. mock.Provide(Factory.Current.Resolve <IReaderToEntityAdapterProvider>()); mock.Provide(Factory.Current.Resolve <Func <ImportFormat, IDataFileReaderService> >( )); mock.Provide(Factory.Current.Resolve <RecordImporter.Factory>( )); mock.Provide(Factory.Current.Resolve <IEntitySaver>( )); return(mock); }