public void HasAppropriateValidators() { var validator = _mock.Create <CompanyRegisterRequestValidator>(); validator .HasPropertyRule(request => request.CompanyName) .HasValidator <NotEmptyValidator, AsyncPredicateValidator>(); validator .HasPropertyRule(request => request.FirstName) .HasValidator <NotEmptyValidator>(); validator .HasPropertyRule(request => request.LastName) .HasValidator <NotEmptyValidator>(); validator .HasPropertyRule(request => request.Email) .HasValidator <EmailValidator, AsyncPredicateValidator>(); validator .HasPropertyRule(request => request.Password) .HasValidator <NotEmptyValidator>(); validator .HasPropertyRule(request => request.ValidationToken) .HasValidator <NotEmptyValidator>(); }
public async Task Stores_New_Jobs() { var jobStarted = new RecordEarningsJob { CollectionPeriod = 1, CollectionYear = 1819, JobId = 1, Ukprn = 9999, IlrSubmissionTime = DateTime.UtcNow.AddMinutes(-20), StartTime = DateTimeOffset.UtcNow, }; var service = mocker.Create <EarningsJobService>(); await service.RecordNewJob(jobStarted, default(CancellationToken)); mocker.Mock <IJobStorageService>() .Verify(x => x.StoreNewJob( It.Is <JobModel>(job => job.StartTime == jobStarted.StartTime && job.JobType == JobType.EarningsJob && job.Status == JobStatus.InProgress && job.DcJobId == jobStarted.JobId && job.CollectionPeriod == jobStarted.CollectionPeriod && job.AcademicYear == jobStarted.CollectionYear && job.IlrSubmissionTime == jobStarted.IlrSubmissionTime && job.Ukprn == jobStarted.Ukprn), It.IsAny <CancellationToken>()), Times.Once); }
public void LoadTheme_ProperlyLoadsThemeWithNoIncludes() { var jObject = JObject.Parse(@"{ 'colors': { 'activityBar.background': '#ff0000' }, 'tokenColors': [{ 'scope': 'tokenColor_scope', 'settings': { 'foreground': 'settings_foreground' } } ] }"); var metadata = new ThemeMetadata { Label = "label_test", ThemeType = "type_test", Path = "test/theme.json" }; _mock.Mock <IJsonFileLoader>() .Setup(x => x.Load(metadata.Path)) .ReturnsAsync(jObject); var mockParser = _mock.Create <VSCodeThemeParser>(); var actual = mockParser.LoadTheme(metadata).Result; Assert.Equal(metadata.Label, actual.Label); Assert.Equal(metadata.ThemeType, actual.ThemeType); Assert.Equal("activityBar.background", actual.Colors[0].PropertyName); Assert.Equal("#ff0000", actual.Colors[0].Value); Assert.Equal("tokenColor_scope", actual.TokenColors[0].Scope); Assert.Equal("settings_foreground", actual.TokenColors[0].Settings.Foreground); }
public async Task SetsBadRequestResultWhenModelIsInvalid() { var actionExecutedContext = ConstractActionExecutingContext(); _mock.Mock <IFactory <ActionExecutingContext, IActionExecutingContext> >() .Setup(factory => factory.Create(actionExecutedContext)) .Returns(_mock.Mock <IActionExecutingContext>().Object); _mock.Mock <IActionExecutingContext>() .Setup(context => context.IsModelValid) .Returns(false); _mock.Mock <IHostingEnvironment>() .Setup(environment => environment.EnvironmentName) .Returns(EnvironmentName.Production); var nextActionMock = new Mock <ActionExecutionDelegate>(); var filter = _mock.Create <Api.Filters.ModelStateFilter.ModelStateFilter>(); await filter.OnActionExecutionAsync(actionExecutedContext, nextActionMock.Object); _mock.Mock <IActionExecutingContext>() .VerifyContent(context => context.SetResult(new BadRequestResult())); nextActionMock .Verify(@delegate => @delegate(), Times.Never()); }
public async Task Publishes_PeriodEndJobFinished_with_SUCCESS_When_PeriodEndJob_Finishes(JobType jobType) { job.JobType = jobType; job.DcJobSucceeded = null; var completedMessage = new CompletedMessage { MessageId = Guid.NewGuid(), JobId = job.Id, Succeeded = true, CompletedTime = DateTimeOffset.UtcNow }; var inProgressMessage = new InProgressMessage { MessageId = completedMessage.MessageId, MessageName = "Message" }; inProgressMessages.Add(inProgressMessage); completedMessages.Add(completedMessage); mocker.Mock <IJobStorageService>() .Setup(x => x.GetJobStatus(It.IsAny <long>(), It.IsAny <CancellationToken>())) .ReturnsAsync((hasFailedMessages: false, endTime: DateTimeOffset.UtcNow.AddSeconds(-10))); var service = mocker.Create <PeriodEndJobStatusService>(); await service.ManageStatus(job.Id, CancellationToken.None).ConfigureAwait(false); mocker.Mock <IJobStatusEventPublisher>() .Verify(publisher => publisher.PeriodEndJobFinished(It.Is <JobModel>(jobModel => jobModel == job) , It.Is <bool>(b => b == true)), Times.Once); mocker.Mock <IJobStatusEventPublisher>() .Verify(publisher => publisher.PeriodEndJobFinished(It.Is <JobModel>(jobModel => jobModel == job) , It.Is <bool>(b => b == false)), Times.Never); }
public void ValidatesFunctionalSkillsWithLearningSupport() { var apprenticeships = CreateApprenticeships(); var earningEvent = CreateEarningEventTestData(); earningEvent.Earnings[0].Type = FunctionalSkillType.LearningSupport; var earningPeriods = new List <EarningPeriod> { earningEvent.Earnings[0].Periods[0] }; var earningProcessor = mocker.Create <FunctionalSkillEarningPeriodsValidationProcessor>(); var periods = earningProcessor.ValidatePeriods( earningEvent.Ukprn, earningEvent.Learner.Uln, earningPeriods, (TransactionType)earningEvent.Earnings[0].Type, apprenticeships, earningEvent.LearningAim, earningEvent.CollectionPeriod.AcademicYear); periods.ValidPeriods.Count.Should().Be(1); periods.ValidPeriods .All(p => p.ApprenticeshipPriceEpisodeId == apprenticeships[0].ApprenticeshipPriceEpisodes[0].Id) .Should().Be(true); }
public void ReturnsExpiresDateForShortTimeToLive() { var now = new DateTime(2018, 5, 3); const int timeToLive = 15; var jwtTokenOptions = new JwtTokenOptions { ExpireMinutesShortToken = timeToLive }; _mock.Mock <INowProvider>() .Setup(provider => provider.Now()) .Returns(now); _mock.Mock <IOptions <JwtTokenOptions> >() .Setup(options => options.Value) .Returns(jwtTokenOptions); var service = _mock.Create <JwtTokenExpireDateTimeProvider>(); var actual = service.Get(false); var expected = now.AddMinutes(timeToLive); Assert.AreEqual(expected, actual); }
public async Task ManageStatus_GiveAtLeastOneTimedOutJobs_FailsWithCompletedWithErrorsStatus() { var jobId = 99; var completedMessage = CreateCompletedMessage(); var inProgressMessage = CreateInProgressMessage(completedMessage); inProgressMessages.Add(inProgressMessage); completedMessages.Add(completedMessage); var timedOutSubmissionJob = CreateTimedOutSubmissionJob(); outstandingOrTimedOutJobs.Add(timedOutSubmissionJob); mocker.Mock <IJobStorageService>() .Setup(x => x.GetJobStatus(It.IsAny <long>(), It.IsAny <CancellationToken>())) .ReturnsAsync((hasFailedMessages: false, endTime: DateTimeOffset.UtcNow.AddSeconds(-10))); var service = mocker.Create <PeriodEndStartJobStatusService>(); var result = await service.ManageStatus(jobId, CancellationToken.None).ConfigureAwait(false); result.Should().BeTrue(); mocker.Mock <IJobStorageService>() .Verify( x => x.SaveJobStatus(It.Is <long>(id => id == jobId), It.Is <JobStatus>(status => status == JobStatus.CompletedWithErrors), It.Is <DateTimeOffset>(endTime => endTime == timedOutSubmissionJob.EndTime), It.IsAny <CancellationToken>()), Times.Once()); }
public void Setup() { BuildConferenceForTest(); _mocker = AutoMock.GetLoose(); _mocker.Mock <IConferenceCache>().Setup(cache => cache.GetOrAddConferenceAsync(_testConference.Id, It.IsAny <Func <Task <ConferenceDetailsResponse> > >())) .Callback(async(Guid anyGuid, Func <Task <ConferenceDetailsResponse> > factory) => await factory()) .ReturnsAsync(_testConference); var parameters = new ParameterBuilder(_mocker) .AddTypedParameters <SharedParticipantRoomMapper>() .Build(); _mocker.Mock <IMapperFactory>() .Setup(x => x.Get <SharedParticipantRoomResponse, Participant, bool, SharedParticipantRoom>()) .Returns(_mocker.Create <SharedParticipantRoomMapper>(parameters)); var claimsPrincipal = new ClaimsPrincipalBuilder().Build(); var context = new ControllerContext { HttpContext = new DefaultHttpContext { User = claimsPrincipal } }; _controller = _mocker.Create <VirtualRoomsController>(); _controller.ControllerContext = context; }
public async Task IsDuplicate_Should_Return_False_For_New_Earning_Events() { var service = mocker.Create <DuplicateEarningEventService>(); var isDuplicate = await service.IsDuplicate(CreateDefaultEarningEvent(), CancellationToken.None).ConfigureAwait(false); isDuplicate.Should().BeFalse(); }
public void ShouldReturnBadRequestWhenOtpAuthTokenClaimNameIsWrong() { const string token = "token"; var parameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, }; var claim = new Claim(ProjectClaims.JwtTokenHasLongTimeToLiveClaimName, ""); var claimsIdentity = new ClaimsIdentity(new Claim[] { claim }, ""); var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); _mock.Mock <ITokenValidationParametersProvider>() .Setup(provider => provider.GetParameters()) .Returns(parameters); _mock.Mock <IJwtSecurityTokenValidator>() .Setup(provider => provider.Validate(token, parameters)) .Returns(claimsPrincipal); _mock.Mock <ClaimsPrincipal>() .Setup(identity => identity.Claims) .Returns(claim.ToEnumerable()); var controller = _mock.Create <UserIdFromOtpTokenProvider>(); ExceptionAssert.Throws <BadRequestException>(() => controller.Get(token)); }
public async Task Returns_True_If_Job_Completed() { job.Status = JobStatus.Completed; var service = mocker.Create <JobStatusService>(); var finished = await service.WaitForJobToFinish(1, CancellationToken.None).ConfigureAwait(false); finished.Should().BeTrue(); }
private void InitContext() { _mock.Mock <IDatabaseFactory>().Setup(x => x.Get()).Returns(GetContext()); var repository = _mock.Create <PriceTresholdRepository>(); var uow = _mock.Create <UnitOfWork>(); _sut = new PriceTresholdService(uow, repository, Mapper); }
public async Task Uses_JObDataContext_To_Get_Job_By_Dc_JobId() { job.Status = JobStatus.Completed; var service = mocker.Create <JobStatusService>(); await service.WaitForJobToFinish(1, CancellationToken.None).ConfigureAwait(false); mocker.Mock <IJobsDataContext>() .Verify(dc => dc.GetJobByDcJobId(It.Is <long>(jobId => jobId == 1)), Times.Once); }
public void SetUp() { mocker = AutoMock.GetLoose(); mockRepository = mocker.Mock <IProvidersRequiringReprocessingRepository>(); testJobs = mocker.Create <List <LatestSuccessfulJobModel> >(); sut = mocker.Create <ProvidersRequiringReprocessingService>(); academicYear = short.MinValue; collectionPeriod = byte.MinValue; }
public async Task ExecuteAsync_InvalidCoupon_Error() { const string someCoupon = "xxxxxx"; _mock.Mock <ICouponRepository>().Setup(s => s.GetCouponAsync(someCoupon, default)).ReturnsAsync((Coupon)null); var command = new ApplyCouponCommand(someCoupon, 0, 0); var instance = _mock.Create <ApplyCouponCommandHandler>(); await Assert.ThrowsAsync <ArgumentException>(() => instance.ExecuteAsync(command, default)); }
public void Uses_Sender_Account_Id_For_Transfers() { var service = mocker.Create <LevyMessageRoutingService>(); var accountId = service.GetDestinationAccountId(new CalculatedRequiredLevyAmount { AccountId = 1, TransferSenderAccountId = 99 }); accountId.Should().Be(99); }
public void RefreshGalleryStore_ProcessesAllGivenItems() { var items = new List <ExtensionMetadata>(); const int itemsCount = 12; for (int i = 0; i < itemsCount; i++) { items.Add(new ExtensionMetadata { Id = $"test_{i}" }); } _mock.Mock <IThemeStoreRefresher>() .Setup(x => x.GetSavedExtensionType(It.IsAny <string>())) .ReturnsAsync(ExtensionType.NoThemes); var mockRefreshService = _mock.Create <ThemeStoreRefreshService>(); mockRefreshService.RefreshGalleryStore(items).Wait(); _mock.Mock <IThemeStoreRefresher>() .Verify( x => x.GetSavedExtensionType(It.IsAny <string>()), Times.Exactly(itemsCount) ); }
public void GetFeatureFlag_Should_Return_True_for_StaffMember_Feature() { _mocker.Mock <IOptions <FeatureFlagConfiguration> >().Setup(opt => opt.Value).Returns(new FeatureFlagConfiguration() { StaffMemberFeature = true }); _service = _mocker.Create <FeatureFlagService>(); var featureFlag = _service.GetFeatureFlag(nameof(FeatureFlags.StaffMemberFeature)); featureFlag.Should().BeTrue(); }
public async Task ReturnsFalseWhenCompanyNameIsNotTaken() { var companyName = "company name"; _mock.Mock <IInventContext>() .Setup(context => context.Companies) .ReturnsAsEmptyDbSet(); var provider = _mock.Create <CompanyNameIsTakenProvider>(); var actual = await provider.IsTaken(companyName); Assert.IsFalse(actual); }
public void ReturnsRenewedToken() { const bool hasLongTimeToLive = true; const string outdatedJwtToken = "outdated bearer token"; const string renewedToken = "renewed token"; var userId = new Guid("{95F0CB0C-C8D6-4105-98F0-721BEDBAEF25}"); var roles = new List <string> { UserRoles.Employee.Name, UserRoles.CompanyAdministrator.Name, }; var claimsPrincipal = new Mock <ClaimsPrincipal>().Object; _mock.Mock <IFactory <ClaimsPrincipal, IUserIdClaimValueProvider> >() .Setup(factory => factory.Create(claimsPrincipal)) .Returns(_mock.Mock <IUserIdClaimValueProvider>().Object); _mock.Mock <IFactory <ClaimsPrincipal, ITokenTTLClaimValueProvider> >() .Setup(factory => factory.Create(claimsPrincipal)) .Returns(_mock.Mock <ITokenTTLClaimValueProvider>().Object); _mock.Mock <IFactory <ClaimsPrincipal, IRolesClaimValueProvider> >() .Setup(factory => factory.Create(claimsPrincipal)) .Returns(_mock.Mock <IRolesClaimValueProvider>().Object); _mock.Mock <ITokenClaimsPrincipalFactory>() .Setup(provider => provider.Create(outdatedJwtToken)) .Returns(claimsPrincipal); _mock.Mock <IUserIdClaimValueProvider>() .Setup(provider => provider.GetValue()) .Returns(userId); _mock.Mock <ITokenTTLClaimValueProvider>() .Setup(provider => provider.HasLongTimeToLive()) .Returns(hasLongTimeToLive); _mock.Mock <IRolesClaimValueProvider>() .Setup(provider => provider.GetValue()) .Returns(roles); _mock.Mock <ICreateJwtTokenAsStringService>() .Setup(instance => instance.Create(userId, hasLongTimeToLive, roles)) .Returns(renewedToken); var service = _mock.Create <RenewAccessTokenService>(); var actual = service.Renew(outdatedJwtToken); Assert.AreEqual(renewedToken, actual); }
public async Task Uses_Correct_Filename_For_In_Period_Submission() { var jobContextMessage = new JobContextMessage { JobId = 1, Topics = new List <ITopicItem> { new TopicItem { SubscriptionName = "GenerateFM36Payments", Tasks = new List <ITaskItem> { new TaskItem { SupportsParallelExecution = false, Tasks = new List <string> { JobContextMessageConstants.Tasks.ProcessSubmission } } } }, new TopicItem { SubscriptionName = "Other Task", Tasks = new List <ITaskItem> { new TaskItem { SupportsParallelExecution = false, Tasks = new List <string> { "Something else" } } } } }, KeyValuePairs = new Dictionary <string, object> { { JobContextMessageConstants.KeyValuePairs.ReturnPeriod, 10 }, { JobContextMessageConstants.KeyValuePairs.CollectionYear, 1819 }, { JobContextMessageConstants.KeyValuePairs.Ukprn, 2123 }, { JobContextMessageConstants.KeyValuePairs.FundingFm36Output, "valid path" }, { JobContextMessageConstants.KeyValuePairs.FundingFm36OutputPeriodEnd, "invalid path" }, { JobContextMessageConstants.KeyValuePairs.Container, "container" }, { JobContextMessageConstants.KeyValuePairs.Filename, "filename" }, } }; var handler = mocker.Create <JobContextMessageHandler>(); await handler.HandleAsync(jobContextMessage, CancellationToken.None); mocker.Mock <IFileService>().Verify(svc => svc.OpenReadStreamAsync( It.Is <string>(file => file.Equals("valid path")), It.Is <string>(containerName => containerName.Equals("container")), It.IsAny <CancellationToken>())); }
public async Task ReturnsEmailIsTaken() { var email = "m@m"; var isTaken = true; _mock.Mock <IEmailIsTakenProvider>() .Setup(provider => provider.IsTaken(email)) .ReturnsAsync(isTaken); var controller = _mock.Create <EmailTakenController>(); var actual = await controller.IsTaken(email); Assert.AreEqual(isTaken, actual); }
public async Task Publishes_SubmissionJobSucceeded_If_Job_Successful() { var submissionTime = DateTime.Now; await mocker.Create <JobStatusEventPublisher>() .SubmissionFinished(true, 99, 1234, 1920, 01, submissionTime); mocker.Mock <IEndpointInstance>() .Verify(x => x.Publish(It.Is <SubmissionJobSucceeded>(ev => ev.JobId == 99 && ev.AcademicYear == 1920 && ev.CollectionPeriod == 01 && ev.IlrSubmissionDateTime == submissionTime && ev.Ukprn == 1234), It.IsAny <PublishOptions>()), Times.Once); }
public void Setup() { _mocker = AutoMock.GetLoose(); _memoryCache = new MemoryCache(new MemoryCacheOptions()); _conferenceCache = new ConferenceCache(_memoryCache); _eventComponentHelper = new EventComponentHelper(); var claimsPrincipal = new ClaimsPrincipalBuilder().Build(); _testConference = _eventComponentHelper.BuildConferenceForTest(); var context = new ControllerContext { HttpContext = new DefaultHttpContext { User = claimsPrincipal } }; var eventHandlerFactory = new EventHandlerFactory(_eventComponentHelper.GetHandlers()); _sut = _mocker.Create <ParticipantsController>(new TypedParameter(typeof(IEventHandlerFactory), eventHandlerFactory), new TypedParameter(typeof(IConferenceCache), _conferenceCache)); _sut.ControllerContext = context; _eventComponentHelper.Cache.Set(_testConference.Id, _testConference); _eventComponentHelper.RegisterUsersForHubContext(_testConference.Participants); }
public void SetUp() { mocker = AutoMock.GetStrict(); eventCacheMock = mocker.Mock <IDataCache <CalculatedRequiredLevyAmount> >(); monthEndCacheMock = mocker.Mock <IDataCache <bool> >(); levyAccountCacheMock = mocker.Mock <IDataCache <LevyAccountModel> >(); levyAccountRepositoryMock = mocker.Mock <ILevyFundingSourceRepository>(); processorMock = mocker.Mock <IPaymentProcessor>(); levyBalanceServiceMock = mocker.Mock <ILevyBalanceService>(); paymentLoggerMock = new Mock <IPaymentLogger>(MockBehavior.Loose); employerProviderPrioritiesMock = mocker.Mock <IDataCache <List <EmployerProviderPriorityModel> > >(); refundSortKeysCacheMock = mocker.Mock <IDataCache <List <string> > >(); transferPaymentSortKeysCacheMock = mocker.Mock <IDataCache <List <TransferPaymentSortKeyModel> > >(); requiredPaymentSortKeysCacheMock = mocker.Mock <IDataCache <List <RequiredPaymentSortKeyModel> > >(); generateSortedPaymentKeysMock = mocker.Mock <IGenerateSortedPaymentKeys>(); service = mocker.Create <RequiredLevyAmountFundingSourceService>( new NamedParameter("mapper", mapper), new NamedParameter("paymentLogger", paymentLoggerMock.Object) ); monthEndCacheMock.Setup(x => x.AddOrReplace(It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <CancellationToken>())) .Returns(Task.CompletedTask); levyAccountCacheMock.Setup(c => c.AddOrReplace(CacheKeys.LevyBalanceKey, It.IsAny <LevyAccountModel>(), It.IsAny <CancellationToken>())) .Returns(Task.CompletedTask); levyBalanceServiceMock.SetupGet(svc => svc.RemainingBalance).Returns(100); levyBalanceServiceMock.SetupGet(svc => svc.RemainingTransferAllowance).Returns(50); }
public void Setup() { _mocker = AutoMock.GetLoose(); var parameters = new ParameterBuilder(_mocker) .AddTypedParameters <ParticipantResponseMapper>() .AddTypedParameters <EndpointsResponseMapper>() .AddTypedParameters <ParticipantForJudgeResponseMapper>() .AddTypedParameters <ParticipantResponseForVhoMapper>() .AddTypedParameters <ParticipantForUserResponseMapper>() .Build(); _mocker.Mock <IMapperFactory>().Setup(x => x.Get <VideoApi.Contract.Responses.ConferenceForJudgeResponse, VideoWeb.Contract.Responses.ConferenceForJudgeResponse>()).Returns(_mocker.Create <ConferenceForJudgeResponseMapper>(parameters)); _mocker.Mock <IMapperFactory>().Setup(x => x.Get <VideoApi.Contract.Responses.ConferenceForIndividualResponse, VideoWeb.Contract.Responses.ConferenceForIndividualResponse>()).Returns(_mocker.Create <ConferenceForIndividualResponseMapper>(parameters)); _mocker.Mock <IMapperFactory>().Setup(x => x.Get <ConferenceForAdminResponse, ConferenceForVhOfficerResponse>()).Returns(_mocker.Create <ConferenceForVhOfficerResponseMapper>(parameters)); _mocker.Mock <IMapperFactory>().Setup(x => x.Get <ConferenceDetailsResponse, ConferenceResponseVho>()).Returns(_mocker.Create <ConferenceResponseVhoMapper>(parameters)); _mocker.Mock <IMapperFactory>().Setup(x => x.Get <ConferenceDetailsResponse, ConferenceResponse>()).Returns(_mocker.Create <ConferenceResponseMapper>(parameters)); var claimsPrincipal = new ClaimsPrincipalBuilder().Build(); var context = new ControllerContext { HttpContext = new DefaultHttpContext { User = claimsPrincipal } }; _controller = _mocker.Create <ConferencesController>(); _controller.ControllerContext = context; _mocker.Mock <IConferenceCache>().Setup(x => x.AddConferenceAsync(It.IsAny <ConferenceDetailsResponse>())); }
public async Task Setup() { _mock = AutoMock.GetLoose(); this._controller = _mock.Create <EventsController>(); this._eventModels = TestsFacade.EventsFacade.BuildEventModels(); //TODO: Instead of Building the event models DTO with the facade use Mapper. this._asyncEventModels = TestsFacade.EventsFacade.BuildIAsyncEnumerable(this._eventModels); this._eventModelsDTOs = await TestsFacade.EventsFacade.BuildEventModelDTOs(this._asyncEventModels); this._eventModelPostsDTOs = TestsFacade.EventsFacade.BuildEventModelPostsDTOs(this._eventModels); this._loggerMock = this._mock.Mock <ILogger <EventsController> >(); this._loggerMock.MockLog(LogLevel.Error); this._loggerMock.MockLog(LogLevel.Information); this._loggerMock.MockLog(LogLevel.Warning); this._userServiceMock = this._mock.Mock <IUserService>(); this._genericServiceMock = this._mock.Mock <IGenericService <EventModel> >(); this._mock.Mock <IMapper>() .Setup(map => map.Map <SearchRequest <EventModel> >(It.IsAny <SearchRequest <EventModelDTO> >())) .Returns(() => new SearchRequest <EventModel>()); this._mock.Mock <IMapper>() .Setup(map => map.Map <IEnumerable <EventModel> >(It.IsAny <IEnumerable <EventModelPostDTO> >())) .Returns(() => this._eventModels); this._mock.Mock <IMapper>() .Setup(map => map.Map <IEnumerable <EventModelDTO> >(It.IsAny <IEnumerable <EventModel> >())) .Returns(() => this._eventModelsDTOs); this._mock.Mock <IMapper>() .Setup(map => map.Map <IEnumerable <EventModelPostDTO> >(It.IsAny <IEnumerable <EventModel> >())) .Returns(() => this._eventModelPostsDTOs); this._mock.Mock <IMapper>() .Setup(map => map.Map <EventModelDTO>(It.IsAny <EventModel>())) .Returns(() => this._eventModelsDTOs.First()); }
public void Setup() { _categoryRepositoryMock = _mock.Mock <ICategoryRepository>(); _postUnitOfWorkMock = _mock.Mock <IPostUnitOfWork>(); _categoryService = _mock.Create <CatergoryService>(); _currentUserServiceMock = _mock.Mock <ICurrentUserService>(); }
public async Task RecipeLookup_WithNegativeFromParameter_ReturnsNoRowsAndWarningAsync() { RecipePayload expected = new RecipePayload(); expected.Q = "chicken"; expected.From = 0; expected.To = 10; expected.More = false; expected.Count = 0; expected.Warning = "Parameter From is less than zero. Please provide a value greater than or equal to zero and less than the To parameter."; expected.Hits = new List <Hit> (); SearchParams searchParams = new SearchParams("chicken", -1, 10); using (AutoMock mock = AutoMock.GetLoose()) { mock.Mock <IApiConfigProvider> () .Setup(x => x.GetApiConfigSettings()) .Returns(new ApiConfigSettings("123", "abc", "hello")); mock.Mock <IRecipeSearchProvider> () .Setup(x => x.RunSearch(searchParams, "123", "abc")) .Returns(Task.FromResult(expected)); RecipeProviderImpl sut = mock.Create <RecipeProviderImpl> (); RecipePayload actual = await sut.GetRecipientsFromSearch(searchParams); Assert.True(JsonCompare.Compare(expected, actual)); } }
private static void RunTest(AutoMock mock) { SetUpSetupations(mock); var component = mock.Create<TestComponent>(); component.RunAll(); }
private static void RunWithSingleSetupationTest(AutoMock mock) { mock.Mock<IServiceB>().Setup(x => x.RunB()); var component = mock.Create<TestComponent>(); component.RunAll(); }
public void Init() { mocker = AutoMock.GetLoose(); banker = mocker.Create<Banker>(); player = mocker.Create<Player>(); }