public async Task ReturnsValidWhenModelWithoutIdIsValid() { const string email = "[email protected]"; var claimsPrincipal = _mock.Mock <ClaimsPrincipal>().Object; var httpContext = _mock.Mock <HttpContext>().Object; var request = new EmployeeDTO { DateOfBirth = DateTime.Now, Email = email, FirstName = "FirstName", LastName = "LastName", Gender = Gender.Female, Phone = "Phone", }; _mock.Mock <HttpContext>() .SetupGet(context => context.User) .Returns(claimsPrincipal); _mock.Mock <IHttpContextAccessor>() .SetupGet(accessor => accessor.HttpContext) .Returns(httpContext); _mock.Mock <IEmailIsTakenProvider>() .Setup(provider => provider.IsTaken(email)) .ReturnsAsync(false); var actual = await _validator.ValidateAsync(request); ContentAssert.AreEqual(new ValidationResult(), actual); }
public void Setup() { _mocker = AutoMock.GetLoose(); _testConference = BuildConferenceForTest(); var claimsPrincipal = new ClaimsPrincipalBuilder().Build(); var context = new ControllerContext { HttpContext = new DefaultHttpContext { User = claimsPrincipal } }; _sut = _mocker.Create <VideoEventsController>(); _sut.ControllerContext = context; var conference = CreateValidConferenceResponse(null); _mocker.Mock <IVideoApiClient>() .Setup(x => x.GetConferenceDetailsByIdAsync(It.IsAny <Guid>())) .ReturnsAsync(conference); _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); _mocker.Mock <IEventHandlerFactory>().Setup(x => x.Get(It.IsAny <EventHub.Enums.EventType>())).Returns(_mocker.Mock <IEventHandler>().Object); }
public async Task ReturnsValidWhenModelIsValid() { const string companyName = "company name"; const string companyPhone = "companyPhone"; const string firstName = "First Name"; const string email = "[email protected]"; const string lastName = "Last Name"; const string password = "******"; const string validationToken = "validation token"; var request = new CompanyRegisterRequest { CompanyName = companyName, CompanyPhone = companyPhone, FirstName = firstName, Email = email, LastName = lastName, Password = password, ValidationToken = validationToken, ToSAccepted = true, }; _mock.Mock <ICompanyNameIsTakenProvider>() .Setup(context => context.IsTaken(companyName)) .ReturnsAsync(false); _mock.Mock <IEmailIsTakenProvider>() .Setup(context => context.IsTaken(email)) .ReturnsAsync(false); var validator = _mock.Create <CompanyRegisterRequestValidator>(); var actual = await validator.ValidateAsync(request); ContentAssert.AreEqual(new ValidationResult(), actual); }
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 void SavePeople_ValidCall() { using (AutoMock mock = AutoMock.GetLoose()) { var person = new PersonModel { Id = 1, FirstName = "Iyad", LastName = "Shobaki", HeightInInches = 71 }; string sql = "insert into Person (FirstName, LastName, HeightInInches) " + "values ('Iyad', 'Shobaki', 71)"; mock.Mock <ISqliteDataAccess>() .Setup(x => x.SaveData(person, sql)); var cls = mock.Create <PersonProcessor>(); cls.SavePerson(person); mock.Mock <ISqliteDataAccess>() .Verify(x => x.SaveData(person, sql), Times.Exactly(1)); } }
static public void Initial(TestContext testContext) { var builder = new ContainerBuilder(); builder.RegisterType <SourceService>().As <ISourceService>().InstancePerDependency(); builder.RegisterType <DestinationService>().As <IDestinationService>().InstancePerDependency(); builder.RegisterType <RecentFileService>().As <IRecentFileService>().InstancePerDependency(); builder.RegisterType <ContosoO365DocSyncDbContext>().AsSelf().InstancePerDependency(); builder.RegisterType <ConfigService>().As <IConfigService>().SingleInstance(); builder.RegisterType <AzureStorageService>().As <IAzureStorageService>().SingleInstance(); builder.RegisterType <LogService>().As <ILogService>().SingleInstance(); builder.RegisterType <MailService>().As <IMailService>().SingleInstance(); builder.RegisterType <UserProfileService>().As <IUserProfileService>().InstancePerDependency(); builder.RegisterType <DocumentService>().As <IDocumentService>().InstancePerDependency(); var mapperConfiguration = new MapperConfiguration(cfg => { cfg.AddProfile(new ServiceMappingProfile()); //This list is keep on going... }); var mapper = mapperConfiguration.CreateMapper(); builder.RegisterInstance(mapper).As <IMapper>().SingleInstance(); Container = builder.Build(); Database.SetInitializer(new MigrateDatabaseToLatestVersion <ContosoO365DocSyncDbContext, ContosoO365DocSync.Service.Migrations.Configuration>()); //InitDatabase(); MockContainer = AutoMock.GetLoose(); MockContainer.Mock <IUserProfileService>().Setup(x => x.GetCurrentUser()).Returns(new UserProfile() { Email = "*****@*****.**", Username = "******" }); MockContainer.Mock <IConfigService>(); //MockContainer.Mock<ILogService>().Setup(x => x.WriteLog(It.IsAny<LogEntity>())); }
public void SetUp() { mocker = AutoMock.GetLoose(); job = new JobModel { Id = 123, Ukprn = 4321, AcademicYear = 1920, CollectionPeriod = 10, DcJobId = 456, JobType = JobType.PeriodEndStartJob, StartTime = DateTimeOffset.UtcNow, LearnerCount = 100, Status = JobStatus.InProgress }; mocker.Mock <IJobsDataContext>() .Setup(dc => dc.GetJobByDcJobId(It.IsAny <long>())) .ReturnsAsync(job); mocker.Mock <IJobStatusConfiguration>() .Setup(cfg => cfg.TimeToPauseBetweenChecks).Returns(TimeSpan.FromMilliseconds(500)); mocker.Mock <IJobStatusConfiguration>() .Setup(cfg => cfg.TimeToWaitForJobToComplete).Returns(TimeSpan.FromSeconds(1)); mocker.Mock <IJobStatusConfiguration>() .Setup(cfg => cfg.TimeToWaitForPeriodEndRunJobToComplete).Returns(TimeSpan.FromSeconds(1)); }
public void Test_Process_Returns_NoResult_If_ObjectAttributesNoteableType_Not_Supported() { using (AutoMock autoMock = AutoMock.GetLoose(this.output.Capture())) { autoMock.Mock <IMockCanHandle>() .Setup(p => p.CanHandle(It.IsAny <string>())) .Returns(false); var processor = autoMock.Create <MockGitlabProcessor>(); RequestProcessResult result = processor.Process(new JObject { [GitlabKeys.ObjectKind] = GitlabKeys.ObjectKindNote, [GitlabKeys.ObjectAttributes] = new JObject { [GitlabKeys.NoteableType] = "some-unsupported-type" } }); Assert.False(result.Success); Assert.True(result.NoResult); Assert.Null(result.Reason); autoMock.Mock <IMockCanHandle>() .Verify(p => p.CanHandle("some-unsupported-type"), Times.Once); } }
public async Task RecipeLookup_MissingSlackSecret_ReturnsNoRowsAndWarningAsync(string slackSecret) { RecipePayload expected = new RecipePayload(); expected.Q = "chicken"; expected.From = 0; expected.To = 10; expected.More = false; expected.Count = 0; expected.Warning = "Configuration Error: Missing SlackSecret."; expected.Hits = new List <Hit> (); SearchParams searchParams = new SearchParams("chicken", 0, 10); using (AutoMock mock = AutoMock.GetLoose()) { mock.Mock <IApiConfigProvider> () .Setup(x => x.GetApiConfigSettings()) .Returns(new ApiConfigSettings("123", "abc", slackSecret)); 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)); } }
public async Task RecipeLookup_WithEmptyStringSearchQuery_ReturnsNoRowsAndWarningAsync( string searchTerm ) { RecipePayload expected = new RecipePayload(); expected.Q = searchTerm; expected.From = 0; expected.To = 10; expected.More = false; expected.Count = 0; expected.Warning = "Search term cannot be empty or null."; expected.Hits = new List <Hit> (); SearchParams searchParams = new SearchParams(searchTerm, 0, 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)); } }
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 void TestSetup() { _billRepositoryMock = _mock.Mock <IBillRepository>(); _billUnitOfWorkMock = _mock.Mock <IBillUnitOfWork>(); _readingRepositoryMock = _mock.Mock <IReadingRepository>(); _readingService = _mock.Create <ReadingService>(); }
public void SetUp() { mocker = AutoMock.GetLoose(); var payments = new List <PaymentModel> { new PaymentModel { Ukprn = Ukprn, Amount = Amount, CollectionPeriod = new CollectionPeriod { Period = 1, AcademicYear = 1920 } }, }; providerPaymentsRepository = mocker.Mock <IProviderPaymentsRepository>(); providerPaymentsRepository .Setup(o => o.GetMonthEndAct1CompletionPayments(It.IsAny <CollectionPeriod>(), It.IsAny <CancellationToken>())) .ReturnsAsync(payments) .Verifiable(); var config = new MapperConfiguration(c => c.AddProfile(typeof(ProviderPaymentsProfile))); var mapper = new Mapper(config); var logger = mocker.Mock <IPaymentLogger>(); completionPaymentService = new CompletionPaymentService(logger.Object, mapper, providerPaymentsRepository.Object); }
public async Task should_return_accepted_if_user_is_vh_officer() { // Arrange var cp = new ClaimsPrincipalBuilder().WithRole(AppRoles.VhOfficerRole) .WithUsername("*****@*****.**").Build(); _sut = SetupControllerWithClaims(cp); var request = new InviteToConsultationRequest { ConferenceId = _testConference.Id, ParticipantId = _testConference.Participants[0].Id, RoomLabel = "Room1" }; // Act var result = await _sut.InviteToConsultationAsync(request); // Assert result.Should().BeOfType <AcceptedResult>(); _mocker.Mock <IConsultationNotifier>() .Verify( x => x.NotifyConsultationRequestAsync(_testConference, "Room1", Guid.Empty, _testConference.Participants[0].Id), Times.Once); }
public async Task ItWillCaptureTransaction(bool captureSuccess) { using (AutoMock mock = AutoMock.GetLoose()) { var paymentMethod = PaymentMethod.CreditCard; var paymentTransaction = GetPaymentTransaction(); var paymentProfile = GetPaymentProfile(); var mockExternalPaymentProcessingService = new MockExternalPaymentProcessingService { TestCallResponseType = captureSuccess ? TestCallResponseType.Succcess : TestCallResponseType.Failure }; mock.Mock <IExternalPaymentFactory>().Setup(x => x.GetPaymentService(It.IsAny <PaymentMethod>())) .Returns(mockExternalPaymentProcessingService); var externalPaymentService = mock.Create <ExternalPaymentService>(); var result = await externalPaymentService.CaptureTransaction(paymentMethod, paymentTransaction, paymentProfile); Assert.NotNull(result); Assert.Equal(captureSuccess, result.IsApproved); mockExternalPaymentProcessingService.VerifyCaptureTransactionCalls(paymentTransaction, paymentProfile); mock.Mock <IExternalPaymentFactory>().Verify(x => x.GetPaymentService(It.Is <PaymentMethod>(p => p == paymentMethod)), Times.Once); } }
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 async Task Should_get_template_by_notification_type_happy() { foreach (var notificationType in Enum.GetValues(typeof(NotificationType)).OfType <NotificationType>()) { // Arrange var template = new Template(Guid.NewGuid(), notificationType, MessageType.Email, "parameters"); _mocker.Mock <IQueryHandler>().Setup(x => x.Handle <GetTemplateByNotificationTypeQuery, Template>(It.Is <GetTemplateByNotificationTypeQuery>(y => y.NotificationType == notificationType))).ReturnsAsync(template); // Act var result = await _sut.GetTemplateByNotificationTypeAsync((Contract.NotificationType) notificationType); // Assert _mocker.Mock <IQueryHandler>().Verify(x => x.Handle <GetTemplateByNotificationTypeQuery, Template>(It.Is <GetTemplateByNotificationTypeQuery>(y => y.NotificationType == notificationType)), Times.Once); result.Should().BeOfType <OkObjectResult>(); var okResult = result as OkObjectResult; okResult.Value.Should().BeOfType <NotificationTemplateResponse>(); var notificationTemplateResponse = okResult.Value as NotificationTemplateResponse; notificationTemplateResponse.Id.Should().Be(template.Id); notificationTemplateResponse.NotificationType.Should().Be((int)notificationType); notificationTemplateResponse.NotifyTemplateId.Should().Be(template.NotifyTemplateId); notificationTemplateResponse.Parameters.Should().Be(template.Parameters); } }
public async Task ShouldUpdateSecurityUser() { var usertId = Guid.NewGuid(); var securityUser = new SecurityUser(); var expected = new UserSettingsDTO(); var userSettingsDTO = new UserSettingsDTO(); _mock.Mock <ISecurityUserProvider>() .Setup(provider => provider.GetByUserIdAsync(usertId)) .ReturnsAsync(securityUser); _mock.Mock <IMapper>() .Setup(mapper => mapper.Map(userSettingsDTO, securityUser)) .Returns(securityUser); _mock.Mock <IMapper>() .Setup(mapper => mapper.Map <UserSettingsDTO>(securityUser)) .Returns(expected); var actual = await _service.UpdateAsync(userSettingsDTO, usertId); _mock.Mock <IInventContext>() .Verify(context => context.Update(securityUser)); _mock.Mock <IInventContext>() .Verify(context => context.SaveChangesAsync(default(CancellationToken))); ContentAssert.AreEqual(expected, actual); }
public async Task ShouldGenerateAndSendPasswordResetToken() { var user = new User() { Id = Guid.NewGuid(), Email = "*****@*****.**" }; var token = "token"; var localizedStringSubject = new LocalizedString("RESET_PASSWORD_EMAIL_SUBJECT", "RESET_PASSWORD_EMAIL_SUBJECT"); var localizedStringBody = new LocalizedString("RESET_PASSWORD_EMAIL_BODY", "RESET_PASSWORD_EMAIL_BODY"); _mock.Mock <IUserManager>() .Setup(x => x.GeneratePasswordResetTokenAsync(user)) .ReturnsAsync(token); _mock.Mock <IStringLocalizer <ResetPasswordService> >() .SetupGet(x => x["RESET_PASSWORD_EMAIL_SUBJECT"]) .Returns(localizedStringSubject); _mock.Mock <IStringLocalizer <ResetPasswordService> >() .SetupGet(x => x["RESET_PASSWORD_EMAIL_BODY"]) .Returns(localizedStringBody); await _resetPasswordService.SendPasswordResetTokenAsync(user); _mock.Mock <ISetPasswordEmailService>() .Verify(context => context.GenerateAndSendTokenAsync(user, token, "/auth/reset", localizedStringSubject, localizedStringBody), Times.Once); }
protected void SetupTestConferenceAndMocks() { Mocker = AutoMock.GetLoose(); TestConference = BuildConferenceForTest(); var claimsPrincipal = new ClaimsPrincipalBuilder().Build(); var context = new ControllerContext { HttpContext = new DefaultHttpContext { User = claimsPrincipal } }; Mocker.Mock <IMapperFactory>().Setup(x => x.Get <ConferenceEventRequest, Conference, CallbackEvent>()).Returns(Mocker.Create <CallbackEventMapper>()); Sut = Mocker.Create <VideoEventsController>(); Sut.ControllerContext = context; var conference = CreateValidConferenceResponse(null); Mocker.Mock <IVideoApiClient>() .Setup(x => x.GetConferenceDetailsByIdAsync(It.IsAny <Guid>())) .ReturnsAsync(conference); 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); Mocker.Mock <IConferenceCache>().Setup(cache => cache.UpdateConferenceAsync(It.IsAny <Conference>())) .Callback <Conference>(updatedConference => { TestConference = updatedConference; }); Mocker.Mock <IEventHandlerFactory>().Setup(x => x.Get(It.IsAny <EventHub.Enums.EventType>())).Returns(Mocker.Mock <IEventHandler>().Object); }
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 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)); } }
public void Test_Process_Calls_MessageClient_If_The_Message_Was_Formatted() { using (AutoMock autoMock = AutoMock.GetLoose(this.output.Capture())) { string mockFormatterResult = "some-result"; autoMock.Mock <IPipelineMessageFormatter>() .Setup(p => p.TryFormat(It.IsAny <JObject>(), out mockFormatterResult)) .Returns(RequestProcessResult.CreateSuccess()); var processor = autoMock.Create <PipelineFailureGitlabProcessor>(); var request = new JObject { [GitlabKeys.ObjectKind] = GitlabKeys.ObjectKindPipeline, [GitlabKeys.ObjectAttributes] = new JObject { [GitlabKeys.Status] = GitlabKeys.StatusFailed } }; RequestProcessResult result = processor.Process(request); Assert.True(result.Success); Assert.False(result.NoResult); Assert.Null(result.Reason); autoMock.Mock <IPipelineMessageFormatter>() .Verify(p => p.TryFormat(request, out mockFormatterResult), Times.Once); autoMock.Mock <IMessageClient>() .Verify(p => p.ScheduleDelivery(mockFormatterResult), Times.Once); } }
public async Task ShouldReturnSecurityUserById() { var securityUserId = Guid.NewGuid(); var expected = new SecurityUser() { Id = securityUserId, }; var securityUsers = new List <SecurityUser>() { expected, new SecurityUser() { Id = Guid.NewGuid(), } }; _mock.Mock <IInventContext>() .Setup(context => context.SecurityUsers) .ReturnsAsDbSet(securityUsers); var actual = await _provider.GetByIdAsync(securityUserId); ContentAssert.AreEqual(expected, actual); }
public void Setup() { _mocker = AutoMock.GetLoose(); var claimsPrincipal = new ClaimsPrincipalBuilder().Build(); var context = new ControllerContext { HttpContext = new DefaultHttpContext { User = claimsPrincipal } }; 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)); _sut = _mocker.Create <ConferencesController>(); _sut.ControllerContext = context; }
public async Task ShouldMarkEployeeAsInvited() { var securityUserId = Guid.NewGuid(); var securityUser = new SecurityUser { Id = securityUserId, IsInvited = false, User = new User() }; _mock.Mock <ISecurityUserProvider>() .Setup(provider => provider.GetByIdAsync(securityUserId)) .ReturnsAsync(securityUser); await _controller.SetInvitationAccepted(securityUserId); Assert.AreEqual(securityUser.IsInvitationAccepted, true); _mock.Mock <IInventContext>() .Verify(context => context.Update(securityUser), Times.Once); _mock.Mock <IInventContext>() .Verify(context => context.SaveChangesAsync(default(CancellationToken)), Times.Once); }
public async Task ShouldSendInvitation() { var employeeId = Guid.NewGuid(); var employee = new Employee { Id = employeeId, SecurityUser = new SecurityUser { Id = Guid.NewGuid(), IsInvited = false, User = new User() } }; _mock.Mock <IEmployeeProvider>() .Setup(provider => provider.GetByIdAsync(employeeId)) .ReturnsAsync(employee); await _service.SendInvitation(employeeId); _mock.Mock <IInviteUserService>() .Verify(service => service.SendPasswordResetTokenAsync(employee.SecurityUser.User), Times.Once); _mock.Mock <IMarkAsInvitedService>() .Verify(service => service.MarkAsync(employee.SecurityUser.Id), Times.Once); }
public void Setup() { _categoryRepositoryMock = _mock.Mock <ICategoryRepository>(); _postUnitOfWorkMock = _mock.Mock <IPostUnitOfWork>(); _categoryService = _mock.Create <CatergoryService>(); _currentUserServiceMock = _mock.Mock <ICurrentUserService>(); }
public async Task Should_return_ok_when_user_is_in_conference() { var conference = CreateValidConferenceResponse(); conference.Participants[0].UserRole = UserRole.Individual; _mocker.Mock <IVideoApiClient>() .Setup(x => x.GetConferenceDetailsByIdAsync(It.IsAny <Guid>())) .ReturnsAsync(conference); var result = await _controller.GetConferenceByIdAsync(conference.Id); var typedResult = (OkObjectResult)result.Result; typedResult.Should().NotBeNull(); var judge = conference.Participants.SingleOrDefault(p => p.UserRole == UserRole.Judge); _mocker.Mock <IConferenceCache>().Verify(x => x.AddConferenceAsync(new ConferenceDetailsResponse()), Times.Never); var response = (ConferenceResponse)typedResult.Value; response.CaseNumber.Should().Be(conference.CaseNumber); response.Participants[0].Role.Should().Be(UserRole.Individual); response.Participants.Any(x => x.Role == Role.Individual).Should().BeTrue(); response.Participants.Any(x => x.Role == Role.Representative).Should().BeTrue(); response.Participants.Any(x => x.Role == Role.Judge).Should().BeTrue(); response.Participants.SingleOrDefault(x => x.Role == Role.Judge).TiledDisplayName.Should().Be($"T{0};{judge.DisplayName};{judge.Id}"); response.Participants.Any(x => x.Role == Role.JudicialOfficeHolder).Should().BeTrue(); }
public async Task RecipeLookup_WithSearchQuery_ReturnsCorrectListAsync() { List <Hit> hits = SampleData.SampleHits(); const string searchTerm = "Chicken"; RecipePayload expected = new RecipePayload(); expected.Q = searchTerm; expected.From = 0; expected.To = 10; expected.More = true; expected.Count = 100000; expected.Warning = ""; expected.Hits = hits; SearchParams searchParams = new SearchParams(searchTerm, 0, 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 SetUpSetupations(AutoMock mock) { mock.Mock<IServiceB>().Setup(x => x.RunB()); mock.Mock<IServiceA>().Setup(x => x.RunA()); }
private static void RunWithSingleSetupationTest(AutoMock mock) { mock.Mock<IServiceB>().Setup(x => x.RunB()); var component = mock.Create<TestComponent>(); component.RunAll(); }
private static void SetUpVerifableSetupations(AutoMock mock) { mock.Mock<IServiceB>().Setup(x => x.RunB()).Verifiable(); mock.Mock<IServiceA>().Setup(x => x.RunA()).Verifiable(); }