public void TestMoqVersionRedirect() { var mocker = new AutoMocker(); mocker.Setup<IMockableThing>(mock => mock.SayHello(It.IsAny<string>())).Returns("Hello Peter"); var sut = mocker.CreateInstance<Fake>(); Assert.That(sut.SayHello("Peter"), Is.EqualTo("Hello Peter")); }
public void SetUp() { var mocker = new AutoMocker(); dataManipulator = mocker.GetMock<IHmrcDataManipulator>(); configRepository = mocker.GetMock<IConfigurationRepository>(); messageSender = mocker.GetMock<IMessageSender>(); messageSender.Setup(x => x.PostXml(It.IsAny<string>(), It.IsAny<string>())).Returns(GetPostResult()); proxyService = mocker.CreateInstance<ProxyService>(); }
public void TestGetCloudantSecurityDocument_Should_Return_A_Valid_Document() { //SETUP var mocker = new AutoMocker(); //connection returns base uri mocker.Setup<ICouchConnection>(c => c.BaseUri).Returns(new Uri("http://localhost")); //GetCouchResponse returns security doc as per Cloudant documentation const string responseString = "{ " + "\"_id\":\"_security\"," + "\"cloudant\":" + "{" + " \"userwithreadonlyaccess\": [" + " \"_reader\"" + " ]," + " \"userwithreadandwriteaccess\": [" + " \"_reader\"," + " \"_writer\"" + " ]" + "}," + "\"ok\":true" + "}"; mocker.Setup<ICouchResponse>(r => r.ResponseString).Returns(responseString); mocker.Setup<ICouchResponse, HttpStatusCode>(r => r.StatusCode).Returns(HttpStatusCode.OK); mocker.Setup<ICouchRequest>(r => r.GetCouchResponse()).Returns(mocker.Get<ICouchResponse>()); //couchFactory returns request mocker.Setup<ICouchFactory>(f => f.GetRequest(It.IsAny<Uri>(), It.IsAny<ICouchConnection>())) .Returns(mocker.Get<ICouchRequest>()); //Get request returns request mocker.Setup<ICouchRequest>(r => r.Get()).Returns(mocker.Get<ICouchRequest>()); //Json content type returns request mocker.Setup<ICouchRequest>(r => r.Json()).Returns(mocker.Get<ICouchRequest>()); //TEST var database = mocker.CreateInstance<CloudantDatabase>(); var securityDocument = (CloudantSecurityDocument)database.GetSecurityDocument(); securityDocument.Id.Should().Be("_security"); securityDocument.CloudantSecuritySection.GetAssignment("userwithreadonlyaccess").Should().BeEquivalentTo("_reader"); securityDocument.CloudantSecuritySection.GetAssignment("userwithreadandwriteaccess").Should().BeEquivalentTo("_reader", "_writer"); securityDocument.Ok.Should().BeTrue(); mocker.VerifyAll(); }
public void EditDiscImageCommand_IfDeletedDiscIsSet_DoesNothing() { // Arrange var disc = new DiscModel().MakeDeleted(); var mocker = new AutoMocker(); var target = mocker.CreateInstance <DiscImageViewModel>(); Messenger.Default.Send(new ActiveDiscChangedEventArgs(disc)); // Act target.EditDiscImageCommand.Execute(null); // Assert var viewNavigatorMock = mocker.GetMock <IViewNavigator>(); viewNavigatorMock.Verify(x => x.ShowEditDiscImageView(It.IsAny <DiscModel>()), Times.Never); }
public void EditDiscImageCommand_IfActiveDiscIsSet_ShowsEditDiscImageViewForDisc() { // Arrange var disc = new DiscModel().MakeActive(); var mocker = new AutoMocker(); var target = mocker.CreateInstance <DiscImageViewModel>(); Messenger.Default.Send(new ActiveDiscChangedEventArgs(disc)); // Act target.EditDiscImageCommand.Execute(null); // Assert var viewNavigatorMock = mocker.GetMock <IViewNavigator>(); viewNavigatorMock.Verify(x => x.ShowEditDiscImageView(disc), Times.Once); }
public async Task GetUserAddressAsync_ShouldReturnResponse() { //Arrange var mocker = new AutoMocker(); var service = mocker.CreateInstance <ContactService>(); var address = GetAddresses(quantity: 1).FirstOrDefault(); var expectedResult = address.ToAddressResponse(); mocker.GetMock <IAddressBus>() .Setup(b => b.GetByUserAsync()) .ReturnsAsync(address) .Verifiable(); //Act var result = await service.GetUserAddressAsync().ConfigureAwait(false); //Assert new CompareLogic().Compare(expectedResult, result).AreEqual.Should().BeTrue(); mocker.Verify(); }
public void CalculateAdviseSetRank_ForListenedAdviseSetWithNoRatingDefined_ReturnsCorrectRank() { // Arrange var adviseGroupContent1 = CreateTestAdviseGroupContent("1", new[] { CreateTestSong(11, rating: null, new DateTime(2021, 06, 28)) }); var adviseGroupContent2 = CreateTestAdviseGroupContent("2", Enumerable.Range(1, 10).Select(id => CreateTestSong(id, RatingModel.R5, new DateTime(2021, 06, 29)))); var playbacksInfo = new PlaybacksInfo(new[] { adviseGroupContent1, adviseGroupContent2 }); var mocker = new AutoMocker(); var target = mocker.CreateInstance <AdviseRankCalculator>(); // Act var rank = target.CalculateAdviseSetRank(adviseGroupContent1.AdviseSets.Single(), playbacksInfo); // Assert // (rating: 1.5 ^ 5) * (playbacks age: 1) rank.Should().Be(7.59375); }
public async Task GetLoginOptions_AuthRequestRequiredButNotAvailable_ReturnsErrorResult() { var automocker = new AutoMocker(); automocker.Setup <IIdentityServerInteractionService, Task <AuthorizationRequest> >(x => x.GetAuthorizationContextAsync("/auth/?authRequest=123")) .ReturnsAsync((AuthorizationRequest)null); automocker .Setup <IOptions <InteractionConfig>, InteractionConfig>(x => x.Value) .Returns(new InteractionConfig { RequireAuthorizationRequest = true }); var target = automocker.CreateInstance <AccountService>(); var result = await target.GetLoginOptions("/auth/?authRequest=123"); result.Should().Be(Option.None <LoginOptions, string>("A valid authorization request is required for login.")); }
public async Task Process_RegisteredHandlerThatReturnsBool_ReturnsSuccessfulResult() { // arrange var autoMocker = new AutoMocker(); var serviceProvider = autoMocker.GetMock <IServiceProvider>(); var testHandler = new Mock <TestHandler>(); serviceProvider.Setup(s => s.GetService(typeof(IHandler <TestRequest, bool>))) .Returns(testHandler.Object); autoMocker.Use <IEnumerable <IInterceptor> >(new List <IInterceptor>()); var sut = autoMocker.CreateInstance <BoltOn.Mediator.Pipeline.Mediator>(); var request = new TestRequest(); testHandler.Setup(s => s.HandleAsync(request, It.IsAny <CancellationToken>())).Returns(Task.FromResult(true)); // act var result = await sut.ProcessAsync(request); // assert Assert.True(result); }
public async Task SongMediaFinishedEventHandler_RegisterPlaybackFinish() { // Arrange var song = new SongModel(); var mocker = new AutoMocker(); var target = mocker.CreateInstance <SongPlayerViewModel>(); await target.Play(song, CancellationToken.None); // Act Messenger.Default.Send(new SongMediaFinishedEventArgs()); // Assert var playbacksRegistrarMock = mocker.GetMock <ISongPlaybacksRegistrar>(); playbacksRegistrarMock.Verify(x => x.RegisterPlaybackFinish(song, It.IsAny <CancellationToken>()), Times.Once); }
public void GetMasterKeyCertificate_NotFoundCertCached_ThrowsException() { var options = new MsisClientCertLocator.Config { CertId = "key-id" }; var cacheKey = nameof(MsisClientCertLocator); object cachedResult = Option.None <X509Certificate2>(); var automocker = new AutoMocker(); automocker.SetupOptions(options); automocker .Setup <IMemoryCache, bool>(x => x.TryGetValue(cacheKey, out cachedResult)) .Returns(true); var target = automocker.CreateInstance <MsisClientCertLocator>(); Assert.Throws <CertificateNotFoundException>(() => target.GetCertificate()); }
public async Task SongMediaFinishedEventHandler_SendsSongPlaybackFinishedEvent() { // Arrange var mocker = new AutoMocker(); var target = mocker.CreateInstance <SongPlayerViewModel>(); SongPlaybackFinishedEventArgs songPlaybackFinishedEvent = null; Messenger.Default.Register <SongPlaybackFinishedEventArgs>(this, e => e.RegisterEvent(ref songPlaybackFinishedEvent)); await target.Play(new SongModel(), CancellationToken.None); // Act Messenger.Default.Send(new SongMediaFinishedEventArgs()); // Assert songPlaybackFinishedEvent.Should().NotBeNull(); }
public void TestProperties() { const double progress = 42; var operationInfo = new OperationInfo(OperationType.Copy, new BinaryFileSystemOperationSettings( new string[0], new string[0], new string[0], new string[0], new Dictionary <string, string>(0), new string[0])); _autoMocker .Setup <ICompositeOperation, OperationInfo>(m => m.Info) .Returns(operationInfo); _autoMocker .Setup <ICompositeOperation, double>(m => m.CurrentProgress) .Returns(progress); var machine = _autoMocker.CreateInstance <AsyncOperationStateMachine>(); Assert.Equal(operationInfo, machine.Info); Assert.Equal(progress, machine.CurrentProgress); }
public void LoadForSongs_SetsCorrectConfirmationMessage() { // Arrange var songs = new[] { new SongModel(), new SongModel(), }; var mocker = new AutoMocker(); var target = mocker.CreateInstance <DeleteContentViewModel>(); // Act target.LoadForSongs(songs); // Assert target.ConfirmationMessage.Should().Be("Do you really want to delete 2 selected song(s)?"); }
public async Task WHEN_calling_VoidPaymentAsync_SHOULD_invoke_Overture_Client() { //Arrange var param = new VoidOrRemovePaymentParam { CartName = GetRandom.String(7), CustomerId = GetRandom.Guid(), CultureInfo = CultureInfo.InvariantCulture, Scope = GetRandom.String(12), PaymentId = GetRandom.Guid() }; var sut = _container.CreateInstance <PaymentRepository>(); //Act await sut.VoidPaymentAsync(param); //Assert _container.Verify <IOvertureClient>(oc => oc.SendAsync(It.IsNotNull <VoidPaymentRequest>())); }
public async Task Logout_GivenShowLogoutPromptOptions_ReturnsLogoutViewResult() { var automocker = new AutoMocker(); automocker.Setup <IAccountService, Task <LogoutOptions> >(x => x.GetLogoutOptions("logout-1", It.IsAny <Option <ClaimsPrincipal> >())) .ReturnsAsync(new LogoutOptions { ShowLogoutPrompt = true }); var target = automocker.CreateInstance <AccountController>().AddTestControllerContext(); var result = await target.Logout("logout-1"); result.Should().BeOfType <ViewResult>(); var vResult = (ViewResult)result; vResult.ViewName.Should().BeNull(); vResult.Model.Should().BeOfType <LogoutViewModel>(); ((LogoutViewModel)vResult.Model).LogoutId.Should().Be("logout-1"); }
public async Task WHEN_Passing_Valid_Parameters_SHOULD_Succeed() { var service = _container.CreateInstance <CheckoutService>(); // Act var result = await service.CompleteCheckoutAsync(new CompleteCheckoutParam { Scope = GetRandom.String(32), CultureInfo = TestingExtensions.GetRandomCulture(), CustomerId = GetRandom.Guid(), CartName = GetRandom.String(32), }); // Assert result.Should().NotBeNull(); }
public async Task ReverseAdviseGroup_IfCurrentAdviseGroupIsNull_AssignsNewAdviseGroup() { // Arrange var adviseGroups = new[] { new AdviseGroupModel { Id = new ItemId("1"), Name = "Advise Group 1" }, new AdviseGroupModel { Id = new ItemId("2"), Name = "Advise Group 2" }, }; var newAdviseGroup = adviseGroups.First(); var adviseGroupServiceStub = new Mock <IAdviseGroupService>(); adviseGroupServiceStub.Setup(x => x.GetAllAdviseGroups(It.IsAny <CancellationToken>())).ReturnsAsync(adviseGroups); var adviseGroupHolderMock = new Mock <BasicAdviseGroupHolder>(); adviseGroupHolderMock.Setup(x => x.CurrentAdviseGroup).Returns <AdviseGroupModel>(null); var mocker = new AutoMocker(); mocker.Use(adviseGroupServiceStub); var target = mocker.CreateInstance <AdviseGroupHelper>(); // Act await target.ReverseAdviseGroup(adviseGroupHolderMock.Object, newAdviseGroup, CancellationToken.None); // Assert adviseGroupHolderMock.Verify(x => x.AssignAdviseGroup(adviseGroupServiceStub.Object, newAdviseGroup, It.IsAny <CancellationToken>()), Times.Once()); target.AdviseGroups.Should().BeEquivalentTo(adviseGroups, x => x.WithStrictOrdering()); }
public async Task UpdateUserAsync_InvalidUser() { //Arrange var comparison = new CompareLogic(); var mocker = new AutoMocker(); var serviceMock = mocker.CreateInstance <UserService>(); var request = GetRequestToUpdate(TestCase.InvalidUser); var userDb = GetUserToUpdate(TestCase.InvalidUser); var tuples = request.Phones.Select(phone => new Tuple <string, string>(phone.LocalCode, phone.Number)).ToList(); var expectedMessages = new string[] { UserSpecMessages.PrimeiroNomeObrigatorio }; mocker.GetMock <IUserBus>() .Setup(b => b.GetByIdAsync(request.Id ?? 0)) .ReturnsAsync(userDb) .Verifiable(); var token = new Entities.TokenModel(userDb.Id, userDb.Email, null); mocker.GetMock <IUserBus>() .Setup(b => b.GetTokenAsync()) .ReturnsAsync(token) .Verifiable(); mocker.GetMock <IUserBus>() .Setup(b => b.ExistsEmailAsync(request.Email, request.Id)) .ReturnsAsync(false) .Verifiable(); //Act var response = await serviceMock.UpdateUserAsync(request).ConfigureAwait(false); //Assert response.Should().BeNull(); serviceMock.IsSatisfied().Should().BeFalse(); Assert.True(serviceMock.GetStatusCode() == HttpStatusCode.BadRequest); Assert.True(comparison.Compare(serviceMock.GetMessages(), expectedMessages).AreEqual); mocker.Verify(); }
public async Task WHEN_valid_request_SHOULD_succeed() { //Arrange var orderStatuses = new Dictionary <string, string>(); var orderHistoryViewModelService = _container.CreateInstance <OrderHistoryViewService>(); _container.GetMock <ILookupService>() .Setup(r => r.GetLookupDisplayNamesAsync(It.IsAny <GetLookupDisplayNamesParam>())) .ReturnsAsync(orderStatuses); _container.GetMock <IOrderRepository>() .Setup(r => r.GetCustomerOrdersAsync(It.IsAny <GetCustomerOrdersParam>())) .ReturnsAsync(new OrderQueryResult { Results = new List <OrderItem>() }); _container.GetMock <IOrderHistoryViewModelFactory>() .Setup(r => r.CreateViewModel(It.IsAny <GetOrderHistoryViewModelParam>())) .Returns(new OrderHistoryViewModel()); _container.GetMock <IOrderUrlProvider>() .Setup(r => r.GetOrderDetailsBaseUrl(It.IsAny <CultureInfo>())) .Returns(GetRandom.String(32)); _container.GetMock <IOrderRepository>() .Setup(r => r.GetOrderSettings(It.IsAny <string>())) .ReturnsAsync(new OrderSettings() { EditableShipmentStates = "new" }); //Act var result = await orderHistoryViewModelService.GetOrderHistoryViewModelAsync(BuildGetCustomerOrdersParam()).ConfigureAwait(false); //Assert result.Should().NotBeNull(); }
public async Task SelectedDiscsCanBeAddedToAdviseSet_IfDiscsBelongsToDifferentAdviseGroups_ReturnsFalse() { // Arrange var discs = new[] { new DiscModel { Id = new ItemId("1"), TreeTitle = "Disc 1" }, new DiscModel { Id = new ItemId("2"), TreeTitle = "Disc 2" }, }; var folder1 = new FolderModel { Id = new ItemId("0"), Name = "<ROOT" }; var folder2 = new FolderModel { Id = new ItemId("1"), Name = "Folder 1" }; folder1.AddSubfolders(folder2); folder1.AddDiscs(discs[0]); folder2.AddDiscs(discs[1]); var mocker = new AutoMocker(); var target = mocker.CreateInstance <AvailableDiscsViewModel>(); await target.LoadDiscs(discs, CancellationToken.None); target.SelectedItems = target.AvailableDiscs; // Act var result = target.SelectedDiscsCanBeAddedToAdviseSet(Array.Empty <DiscModel>()); // Assert result.Should().BeFalse(); }
public async Task GetActiveValidationKeys_GivenRolloverAndMasterKeyCert_ReturnsKeysIncludingRollover() { //Arrange var automocker = new AutoMocker(); var masterKey = new byte[256]; object cachedResult = null; automocker .SetupOptions(new AnonymousTokensConfig { KeyRotationEnabled = true, CurveName = "P-256", MasterKeyCertId = "master-key-cert", KeyRotationInterval = TimeSpan.FromDays(3), KeyRotationRollover = TimeSpan.FromDays(4) }); automocker .Setup <IMemoryCache, bool>(x => x.TryGetValue(It.IsAny <string>(), out cachedResult)) .Returns(false); automocker .Setup <IMemoryCache, ICacheEntry>(x => x.CreateEntry(It.IsAny <string>())) .Returns(Mock.Of <ICacheEntry>()); automocker .Setup <IAnonymousTokenMasterKeyLoader, Task <byte[]> >(x => x.LoadMasterKeyBytes()) .ReturnsAsync(masterKey); var target = automocker.CreateInstance <AnonymousTokenKeyStore>(); //Act var result = (await target.GetActiveValidationKeys()).ToList(); //Assert result.Should().HaveCountGreaterThan(1); result.Should().NotContain(c => c.PublicKey == null); }
public async Task GetActiveValidationKeys_GivenNoRotationAndMasterKeyCert_ReturnsOneValidationKey() { //Arrange var automocker = new AutoMocker(); var masterKey = new byte[256]; object cachedResult; automocker .SetupOptions(new AnonymousTokensConfig { KeyRotationEnabled = false, CurveName = "P-256", MasterKeyCertId = "master-key-cert" }); automocker .Setup <IMemoryCache, bool>(x => x.TryGetValue(It.IsAny <string>(), out cachedResult)) .Returns(false); automocker .Setup <IMemoryCache, ICacheEntry>(x => x.CreateEntry(It.IsAny <string>())) .Returns(Mock.Of <ICacheEntry>()); automocker .Setup <IAnonymousTokenMasterKeyLoader, Task <byte[]> >(x => x.LoadMasterKeyBytes()) .ReturnsAsync(masterKey); var target = automocker.CreateInstance <AnonymousTokenKeyStore>(); //Act var result = (await target.GetActiveValidationKeys()).ToList(); //Assert result.Should().HaveCount(1); var key = result.First(); key.PublicKey.Should().NotBeNull(); }
public async Task SyncAsync_When_GarminUpload_StepFails_Should_ReturnCorrectResponse() { // SETUP var mocker = new AutoMocker(); var config = new Settings(); var service = mocker.CreateInstance <SyncService>(); var peloton = mocker.GetMock <IPelotonService>(); var db = mocker.GetMock <ISyncStatusDb>(); var converter = mocker.GetMock <IConverter>(); var garmin = mocker.GetMock <IGarminUploader>(); var syncStatus = new SyncServiceStatus(); db.Setup(x => x.GetSyncStatusAsync()).Returns(Task.FromResult(syncStatus)); peloton.Setup(x => x.GetRecentWorkoutsAsync(0)).ReturnsAsync(new List <RecentWorkout>() { new RecentWorkout() { Status = "COMPLETE", Id = "1" } }); peloton.Setup(x => x.GetWorkoutDetailsAsync(It.IsAny <ICollection <RecentWorkout> >())).ReturnsAsync(new P2GWorkout[] { new P2GWorkout() }); garmin.Setup(x => x.UploadToGarminAsync()).Throws(new Exception()); // ACT var response = await service.SyncAsync(0); // ASSERT response.SyncSuccess.Should().BeFalse(); response.PelotonDownloadSuccess.Should().BeTrue(); response.ConversionSuccess.Should().BeTrue(); response.UploadToGarminSuccess.Should().BeFalse(); response.Errors.Should().NotBeNullOrEmpty(); peloton.Verify(x => x.GetRecentWorkoutsAsync(0), Times.Once); converter.Verify(x => x.Convert(It.IsAny <P2GWorkout>()), Times.Once); garmin.Verify(x => x.UploadToGarminAsync(), Times.Once); db.Verify(x => x.UpsertSyncStatusAsync(It.IsAny <SyncServiceStatus>()), Times.Once); }
public async Task OnImport_WhenItemMatchesExistingTransaction_IsMarkedDone() { var mocker = new AutoMocker().WithDefaults(); using var factory = mocker.WithDbScope(); using var context = factory.Create(); var date = DateTime.Today.AddDays(-2); var category = new ExpenseCategory(); context.ExpenseCategories.Add(category); await context.SaveChangesAsync(); var item = new ExpenseCategoryItem { Date = date, Description = "Existing item", Details = new() { new ExpenseCategoryItemDetail { Amount = -10_71, ExpenseCategory = category } } }; context.ExpenseCategoryItems.Add(item); await context.SaveChangesAsync(); var vm = mocker.CreateInstance <ImportViewModel>(); vm.CsvData = TestCSVData.SingleTransaction; await vm.ImportCommand.ExecuteAsync(null); ImportItem importItem = vm.ImportedRecords.Single(); Assert.IsTrue(importItem.IsDone); }
public void Process_MediatorWithCommandRequest_ExecutesUoWInterceptorAndStartsTransactionsWithDefaultCommandIsolationLevel() { // arrange var autoMocker = new AutoMocker(); var serviceProvider = autoMocker.GetMock <IServiceProvider>(); var testHandler = new Mock <TestHandler>(); var interceptor = new Mock <IInterceptor>(); var logger = new Mock <IBoltOnLogger <UnitOfWorkInterceptor> >(); serviceProvider.Setup(s => s.GetService(typeof(IRequestHandler <TestCommand, bool>))) .Returns(testHandler.Object); var uowManager = autoMocker.GetMock <IUnitOfWorkManager>(); var uow = new Mock <IUnitOfWork>(); uowManager.Setup(u => u.Get(It.IsAny <UnitOfWorkOptions>())).Returns(uow.Object); var uowOptions = autoMocker.GetMock <UnitOfWorkOptions>(); uowOptions.Setup(u => u.IsolationLevel).Returns(IsolationLevel.ReadCommitted); var uowOptionsBuilder = autoMocker.GetMock <IUnitOfWorkOptionsBuilder>(); var request = new TestCommand(); uowOptionsBuilder.Setup(u => u.Build(request)).Returns(uowOptions.Object); autoMocker.Use <IEnumerable <IInterceptor> >(new List <IInterceptor> { new UnitOfWorkInterceptor(logger.Object, uowManager.Object, uowOptionsBuilder.Object) }); var sut = autoMocker.CreateInstance <BoltOn.Mediator.Pipeline.Mediator>(); testHandler.Setup(s => s.Handle(request)).Returns(true); // act var result = sut.Process(request); // assert Assert.True(result); uowManager.Verify(u => u.Get(uowOptions.Object)); uow.Verify(u => u.Commit()); logger.Verify(l => l.Debug($"About to start UoW with IsolationLevel: {IsolationLevel.ReadCommitted.ToString()}")); logger.Verify(l => l.Debug("UnitOfWorkInterceptor ended")); }
public async Task GetPolicyAsync_GivenKnownPolicyAllowedOrigin_ReturnsAllowAllPolicy() { var automocker = new AutoMocker(); automocker .Setup <ICorsPolicyService, Task <bool> >(x => x.IsOriginAllowedAsync("http://is.allowed.com")) .ReturnsAsync(true); var serviceProviderMock = new Mock <IServiceProvider>(); serviceProviderMock .Setup(x => x.GetService(It.IsAny <Type>())) .Returns <Type>(t => automocker.Get(t)); var httpContext = new DefaultHttpContext { Request = { Headers = { { "Origin", "http://is.allowed.com" } } }, RequestServices = serviceProviderMock.Object }; var target = automocker.CreateInstance <CustomCorsPolicyProvider>(); var result = await target.GetPolicyAsync(httpContext, CorsPolicies.AnonymousTokens); using (new AssertionScope()) { result.Should().NotBeNull(); result.AllowAnyHeader.Should().BeTrue(); result.AllowAnyMethod.Should().BeTrue(); result.Origins.Should().HaveCount(1).And.Contain("http://is.allowed.com"); } }
public void TestSortingParentDirectory(bool isAscending, SortingMode sortingColumn) { var parentDirectoryViewModel = _autoMocker.CreateInstance <DirectoryViewModel>(); parentDirectoryViewModel.IsParentDirectory = true; var directoryViewModel = _autoMocker.CreateInstance <DirectoryViewModel>(); var comparer = new DirectoryViewModelsComparer(isAscending, sortingColumn); var result = comparer.Compare(parentDirectoryViewModel, directoryViewModel); Assert.True(result < 0); result = comparer.Compare(directoryViewModel, parentDirectoryViewModel); Assert.True(result > 0); }
public void ListInfoProperties_ForNonEmptySongList_ReturnCorrectValues() { // Arrange var songs = new[] { new SongModel { Id = new ItemId("0"), Size = 123, Duration = new TimeSpan(0, 3, 28), }, new SongModel { Id = new ItemId("1"), Size = 12345, Duration = new TimeSpan(0, 4, 11), }, }; var mocker = new AutoMocker(); var target = mocker.CreateInstance <TestSongListViewModel>(); target.SetSongs(songs); // Act var hasSongs = target.HasSongs; var songsNumber = target.SongsNumber; var totalSongsFileSize = target.TotalSongsFileSize; var totalSongsDuration = target.TotalSongsDuration; // Assert hasSongs.Should().BeTrue(); songsNumber.Should().Be(2); totalSongsFileSize.Should().Be("12.2 KB"); totalSongsDuration.Should().Be(new TimeSpan(0, 7, 39)); }
public async Task HandleNotificationAsync_JoinedGuildNotification_GuildIsAvailable_InvokesAutoConfigureGuildAsync() { var autoMocker = new AutoMocker(); var uut = autoMocker.CreateInstance <AuthorizationAutoConfigBehavior>(); var mockGuild = autoMocker.GetMock <ISocketGuild>(); mockGuild .Setup(x => x.Available) .Returns(true); using (var cancellationTokenSource = new CancellationTokenSource()) { var notification = new JoinedGuildNotification(mockGuild.Object); await uut.HandleNotificationAsync(notification, cancellationTokenSource.Token); autoMocker.GetMock <IAuthorizationService>() .ShouldHaveReceived(x => x.AutoConfigureGuildAsync(mockGuild.Object, cancellationTokenSource.Token)); } }
public async void GetById_test() { // Given var mocker = new AutoMocker(); var pedidoServiceMock = mocker.CreateInstance <PedidoService>(); var faker = AutoFaker.Create(); var drone = faker.Generate <Drone>(); // var pedido = faker.Generate<Pedido>(); var pedidoFaker = new AutoFaker <Pedido>() .RuleFor(u => u.DroneId, f => f.Random.Int(1)); var pedido = pedidoFaker.Generate(); var responseDroneTask = Task.Factory.StartNew(() => drone); var responsePedidoTask = Task.Factory.StartNew(() => pedido); var expectResponse = pedido; // pedidoServiceMock.GetById(responsePedido); var droneRepository = mocker.GetMock <IDroneRepository>(); var pedidoRepository = mocker.GetMock <IPedidoRepository>(); droneRepository.Setup(r => r.ObterPorId(It.IsAny <Int32>())).Returns(responseDroneTask).Verifiable(); pedidoRepository.Setup(r => r.ObterPorId(It.IsAny <Guid>())).Returns(responsePedidoTask).Verifiable(); //When var result = await pedidoServiceMock.GetById(It.IsAny <Guid>()); //Then droneRepository.Verify(mock => mock.ObterPorId(It.IsAny <Int32>()), Times.Once()); pedidoRepository.Verify(mock => mock.ObterPorId(It.IsAny <Guid>()), Times.Once()); CompareLogic comparer = new CompareLogic(); Assert.True(comparer.Compare(expectResponse, result).AreEqual); }
public void Init() { _mocker = new AutoMocker(); _audioDramas = new SampleAudioDramaProvider().Get().ToList(); _mocker .Setup <IPresenter <IAudioDramaView, AudioDrama>, IAudioDramaView>(x => x.GetView()) .Returns(_mocker.Get <IAudioDramaView>()); _mocker.Setup <IPresenter <IAudioDramaListView, IEnumerable <AudioDrama> >, IAudioDramaListView>(x => x.GetView()) .Returns(_mocker.Get <IAudioDramaListView>()); _mocker.Use(typeof(IEnumerable <AudioDrama>), _audioDramas); _mocker .Setup <ISource <IEnumerable <AudioDrama> >, IEnumerable <AudioDrama> >(x => x.Get()) .Returns(_audioDramas); _navigator = _mocker.CreateInstance <Navigator>(); }
public async Task WHEN_valid_request_SHOULD_succeed() { //Arrange var expectedCustomer = MockCustomerFactory.CreateRandom(); var customerRepository = _container.CreateInstance <CustomerRepository>(); _container.GetMock <IOvertureClient>() .Setup(r => r.SendAsync(It.IsAny <UpdateCustomerRequest>())) .ReturnsAsync(expectedCustomer); //Act var result = await customerRepository.UpdateUserAsync( new UpdateUserParam { Customer = expectedCustomer, Scope = GetRandom.String(32) } ); //Assert result.Id.Should().Be(expectedCustomer.Id); }
public void TestUpdateSecurityDoc_Should_Succeed_For_Valid_Document() { //SETUP var mocker = new AutoMocker(); //connection returns base uri mocker.Setup<ICouchConnection>(c => c.BaseUri).Returns(new Uri("http://localhost")); //GetCouchResponse returns security doc as per Cloudant documentation const string responseString = "{ " + "\"ok\":true" + "}"; mocker.Setup<ICouchResponse>(r => r.ResponseString).Returns(responseString); mocker.Setup<ICouchResponse, HttpStatusCode>(r => r.StatusCode).Returns(HttpStatusCode.OK); mocker.Setup<ICouchRequest>(r => r.GetCouchResponse()).Returns(mocker.Get<ICouchResponse>()); //couchFactory returns request mocker.Setup<ICouchFactory>(f => f.GetRequest(It.IsAny<Uri>(), It.IsAny<ICouchConnection>())) .Returns(mocker.Get<ICouchRequest>()); //Get request returns request mocker.Setup<ICouchRequest>(r => r.Put()).Returns(mocker.Get<ICouchRequest>()); //Json content type returns request mocker.Setup<ICouchRequest>(r => r.Json()).Returns(mocker.Get<ICouchRequest>()); //Data returns request mocker.Setup<ICouchRequest>(r => r.Data(It.IsAny<string>())).Returns(mocker.Get<ICouchRequest>()); //security doc var securityDoc = new CloudantSecurityDocument(); securityDoc.CloudantSecuritySection.AddUser("user1", "_reader"); securityDoc.CloudantSecuritySection.AddUser("user2", "_reader","_writer"); //TEST var database = mocker.CreateInstance<CloudantDatabase>(); database.UpdateSecurityDocument(securityDoc); mocker.VerifyAll(); }
public void It_creates_mock_objects_for_ctor_parameters_with_supplied_behavior() { var strictMocker = new AutoMocker(MockBehavior.Strict); var instance = strictMocker.CreateInstance<OneConstructor>(); var mock = Mock.Get(instance.Empty); mock.ShouldNotBeNull(); mock.Behavior.ShouldEqual(MockBehavior.Strict); }
private static ContentFragment CreateFragment(string internalFormat) { var mocker = new AutoMocker(); mocker.Use<TemplateModelSelector>(mocker.CreateInstance<TemplateModelSelector>()); mocker.Use<DisplayChannelService>(mocker.CreateInstance<DisplayChannelService>()); mocker.Use<TemplateModelRepository>(mocker.CreateInstance<TemplateModelRepository>()); mocker.Use<TemplateResolver>(mocker.CreateInstance<TemplateResolver>()); mocker.Use<TemplateControlLoader>(mocker.CreateInstance<TemplateControlLoader>()); var fragment = new Mock<ContentFragment>(Mock.Of<IContentLoader>(), mocker.CreateInstance<TemplateControlLoader>(), Mock.Of<ISecuredFragmentMarkupGenerator>()); fragment.SetupGet(x => x.InternalFormat).Returns(internalFormat); return fragment.Object; }
public void TemplateType_AngularJsPrototype_Not_Found() { //Arrange AutoMocker mocker = new AutoMocker(); var proxySettings = new ProxySettings(); proxySettings.Templates.Add(new TemplateEntry() { TemplateType = TemplateTypes.AngularJsModule }); mocker.Use<IProxyGeneratorFactoryManager>(new ProxyGeneratorFactoryManager(proxySettings)); var myMock = mocker.CreateInstance<AngularJsProxyBuilder>(); //Act var generatedProxyEntries = myMock.BuildProxy(new List<ProxyControllerInfo>()); }