public void TestAddingRecordingDeviceToSelected() { var configurationMoq = new Mock<ISoundSwitchConfiguration> {Name = "Configuration mock"}; var audioMoqI = new Mock<IAudioDevice> {Name = "first audio dev"}; audioMoqI.SetupGet(a => a.FriendlyName).Returns("Speakers (Test device)"); audioMoqI.SetupGet(a => a.Type).Returns(AudioDeviceType.Recording); //Setup configurationMoq.Setup(c => c.SelectedRecordingDeviceList).Returns(new HashSet<string>()); TestHelpers.SetConfigurationMoq(configurationMoq); //Action var eventCalled = false; AppModel.Instance.SelectedDeviceChanged += (sender, changed) => eventCalled = true; Assert.True(AppModel.Instance.SelectDevice(audioMoqI.Object)); //Asserts configurationMoq.VerifyGet(c => c.SelectedRecordingDeviceList); configurationMoq.Verify(c => c.Save()); audioMoqI.VerifyGet(a => a.FriendlyName); audioMoqI.VerifyGet(a => a.Type); Assert.That(configurationMoq.Object.SelectedRecordingDeviceList.Count == 1); Assert.That(configurationMoq.Object.SelectedRecordingDeviceList.Contains("Speakers (Test device)")); Assert.That(eventCalled, "SelectedDeviceChanged not called"); }
public void When_all_Rovers_deployed_requests_Rover_Positions_and_CardinalDirections() { var mockRover = new Mock<IRover>(); mockRover.Setup(x => x.IsDeployed()).Returns(true); var rovers = new List<IRover> {mockRover.Object, mockRover.Object, mockRover.Object}; var reportComposer = new ConsoleReportComposer(); reportComposer.CompileReports(rovers); mockRover.VerifyGet(x => x.Position, Times.Exactly(3)); mockRover.VerifyGet(x => x.CardinalDirection, Times.Exactly(3)); }
public void AucunRafraichissementNestFaitSiLaValeurEstVide() { FiltrePresenter presenter = new FiltrePresenter(Vue, Repository.Object); Mock<IFiltreView> mock = new Mock<IFiltreView>(); mock.SetupGet(vue => vue.BlockAffichageFiltres).Verifiable(); mock.SetupGet(vue => vue.ListeBoxVille).Verifiable(); presenter.ActualiseLaListeDeFiltre(string.Empty, mock.Object.ListeBoxVille); //On passe une fois par le get de la listBox lors du passage de paramètre mock.VerifyGet(vue => vue.ListeBoxVille, Times.Exactly(1)); mock.VerifyGet(vue => vue.BlockAffichageFiltres, Times.Never()); }
public void CreateAssignedWorkStation_ValidCommand_Verify_WorkStationId_Get_From_ApplicationSettings_Using_Setup_Property() { //Arrange var createCommmand = new CustomerCreateCommand() { FirstName = "Mohamed", LastName = "Ahmed" }; var mockCustomerRepository = new Mock<ICustomerRepository>(); var mockApplicationSettings = new Mock<IApplicationSettings>(); mockCustomerRepository.Setup(x => x.Save(It.IsAny<Customer>())); //mockApplicationSettings.Setup(x => x.WorkStationId) // .Returns(10); mockApplicationSettings.SetupProperty(x => x.WorkStationId, 123); //Can we set if from the object itself?? //mockApplicationSettings.Object.WorkStationId = 345; //mockApplicationSettings.SetupAllProperties(); CustomerService_8 customerService = new CustomerService_8( mockCustomerRepository.Object, mockApplicationSettings.Object ); //Act customerService.CreateAssignedWorkStation(createCommmand); //Assert mockApplicationSettings.VerifyGet(x => x.WorkStationId); }
public void CreateAssignedWorkStation_ValidCommand_Verify_WorkStationId_Get_From_ApplicationSettings() { //Arrange var createCommmand = new CustomerCreateCommand() { FirstName = "Mohamed", LastName = "Ahmed" }; var mockCustomerRepository = new Mock<ICustomerRepository>(); var mockApplicationSettings = new Mock<IApplicationSettings>(); mockCustomerRepository.Setup(x => x.Save(It.IsAny<Customer>())); mockApplicationSettings.Setup(x => x.WorkStationId) .Returns(10); CustomerService_8 customerService = new CustomerService_8( mockCustomerRepository.Object, mockApplicationSettings.Object ); //Act customerService.CreateAssignedWorkStation(createCommmand); //Assert mockApplicationSettings.VerifyGet(x => x.WorkStationId); }
private void Example() { var mock = new Mock<IFoo>(); mock.Verify(foo => foo.Execute("ping")); // Verify with custom error message for failure mock.Verify(foo => foo.Execute("ping"), "When doing operation X, the service should be pinged always"); // Method should never be called mock.Verify(foo => foo.Execute("ping"), Times.Never()); // Called at least once mock.Verify(foo => foo.Execute("ping"), Times.AtLeastOnce()); mock.VerifyGet(foo => foo.Name); // Verify setter invocation, regardless of value. mock.VerifySet(foo => foo.Name); // Verify setter called with specific value mock.VerifySet(foo => foo.Name = "foo"); // Verify setter with an argument matcher mock.VerifySet(foo => foo.Value = It.IsInRange(1, 5, Range.Inclusive)); }
public void WatchedDirectoryConfigureWhenStrategyNotDefinedPullsValuesFromWatchDirectoryProperly() { // Arrange var testBundle = new WatchedDirectoryTestBundle(); var mockWatchDirectory = new Mock<IWatchDirectory>(); mockWatchDirectory.SetupGet(x => x.FileExtensions).Returns("abc"); // Act testBundle.WatchedDirectory.Configure(mockWatchDirectory.Object); // Assert mockWatchDirectory.VerifyGet(x => x.Path, Times.Once()); mockWatchDirectory.VerifyGet(x => x.IncludeSubDirectories, Times.Once()); mockWatchDirectory.VerifyGet(x => x.Mode, Times.Once()); mockWatchDirectory.VerifyGet(x => x.SortStrategy, Times.Once()); mockWatchDirectory.VerifyGet(x => x.FileExtensions, Times.Once()); }
public void EqualityCheckAspect_Can_Be_Applied_To_ValueType() { var mock = new Mock<MockEqualityChecked> {CallBase = true}; var underTest = mock.Object; underTest.Flag = true; underTest.Flag = true; mock.VerifyGet(x=>x.Flag, Times.AtLeast(2)); mock.Verify(x=>x.SetFlag(It.IsAny<bool>()), Times.Once()); }
public void WrapsConnectionTimeout() { var mockConn = new Mock<IAdomdConnection>(); mockConn.SetupGet(p => p.ConnectionTimeout).Returns(30); var conn = new GlimpseAdomdConnection(mockConn.Object, new Mock<ITimedMessagePublisher>().Object); Assert.That(conn.ConnectionTimeout, Is.EqualTo(30)); mockConn.VerifyGet(p => p.ConnectionTimeout, Times.Once); }
public void WrapsDatabase() { var mockConn = new Mock<IAdomdConnection>(); mockConn.SetupGet(p => p.Database).Returns("TEST"); var conn = new GlimpseAdomdConnection(mockConn.Object, new Mock<ITimedMessagePublisher>().Object); Assert.That(conn.Database, Is.EqualTo("TEST")); mockConn.VerifyGet(p => p.Database, Times.Once); }
public void Integration() { var discountMock = new Mock<IOrderDiscount>(); discountMock.SetupGet(m => m.MemberGroups).Returns(new List<string>()); discountMock.SetupGet(m => m.AffectedOrderlines).Returns(new List<int>()); _discountCalculationService.DiscountAmountForOrder(discountMock.Object, _order); discountMock.VerifyGet(m => m.AffectedProductTags); }
public void filereader_is_transparent() { var settings = new Mock<ISettingsReader>(); settings.SetupGet(m => m["hue"]).Verifiable(); var filereader = new FileReader(@"data\FileSettingsReaderTestData", settings.Object); filereader.EnsureKey("hue", "9"); var crap = filereader["hue"]; var stuff = filereader.Keys; filereader.Settings = "new settings"; crap = filereader.Settings; settings.Verify(m => m.EnsureKey("hue", "9"), Times.AtLeastOnce()); settings.VerifyGet(m => m.Keys, Times.AtLeastOnce()); settings.VerifyGet(m => m.Settings, Times.AtLeastOnce()); settings.VerifySet(m => { m.Settings = "new settings"; }, Times.AtLeastOnce()); settings.Verify(); }
public void WrapsConnectionString() { var mockConn = new Mock<IAdomdConnection>(); mockConn.SetupProperty(p => p.ConnectionString, "TEST"); var conn = new GlimpseAdomdConnection(mockConn.Object, new Mock<ITimedMessagePublisher>().Object); Assert.That(conn.ConnectionString, Is.EqualTo("TEST")); mockConn.VerifyGet(p => p.ConnectionString, Times.Once); conn.ConnectionString = "ABC"; Assert.That(conn.ConnectionString, Is.EqualTo("ABC")); mockConn.VerifySet(p => p.ConnectionString = It.Is<string>(s => s == "ABC"), Times.Once); }
public void CallingTableReturnsRenameTableExpressionBuilder() { var collectionMock = new Mock<ICollection<IMigrationExpression>>(); var contextMock = new Mock<IMigrationContext>(); contextMock.SetupGet(x => x.Expressions).Returns(collectionMock.Object); var root = new RenameExpressionRoot(contextMock.Object); var builder = root.Table("Bacon"); builder.ShouldBeOfType<RenameTableExpressionBuilder>(); contextMock.VerifyGet(x => x.Expressions); }
public void CallingColumnReturnsDeleteColumnExpressionBuilder() { var collectionMock = new Mock<ICollection<IMigrationExpression>>(); var contextMock = new Mock<IMigrationContext>(); contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object); var root = new DeleteExpressionRoot(contextMock.Object); var builder = root.Column("Bacon"); builder.ShouldBeOfType<DeleteColumnExpressionBuilder>(); contextMock.VerifyGet(x => x.Expressions); }
public void CallingColumnReturnsAlterColumnExpression() { var collectionMock = new Mock<ICollection<IMigrationExpression>>(); var contextMock = new Mock<IMigrationContext>(); contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object); contextMock.VerifyGet(x => x.Expressions, Times.AtMostOnce()); var root = new AlterExpressionRoot(contextMock.Object); var builder = root.Column("Bacon"); builder.ShouldBeOfType<AlterColumnExpressionBuilder>(); contextMock.VerifyAll(); }
public void CallingTableAddsRenameTableExpressionToContextWithSpecifiedOldName() { var collectionMock = new Mock<ICollection<IMigrationExpression>>(); var contextMock = new Mock<IMigrationContext>(); contextMock.SetupGet(x => x.Expressions).Returns(collectionMock.Object); var root = new RenameExpressionRoot(contextMock.Object); root.Table("Bacon"); collectionMock.Verify(x => x.Add(It.Is<RenameTableExpression>(e => e.OldName.Equals("Bacon")))); contextMock.VerifyGet(x => x.Expressions); }
public void TestIfOnTargetGetItUsesTheFuncOnTheParentField() { // Arrange var parentMock = new Mock<Parent>(); var target = new ItsAssertable<Parent, Child>(p => p.Child); target.SetFieldValue("mParent", parentMock.Object); // Act var result = target.Target; // Assert parentMock.VerifyGet(m => m.Child, Times.Once()); }
public void CallingToTableSetsPrimaryTableName() { var foreignKeyMock = new Mock<ForeignKeyDefinition>(); var expressionMock = new Mock<DeleteForeignKeyExpression>(); expressionMock.SetupGet(e => e.ForeignKey).Returns(foreignKeyMock.Object); var builder = new DeleteForeignKeyExpressionBuilder(expressionMock.Object); builder.ToTable("Bacon"); foreignKeyMock.VerifySet(f => f.PrimaryTable = "Bacon"); expressionMock.VerifyGet(e => e.ForeignKey); }
public void CallingOnTableSetsForeignTableName() { var foreignKeyMock = new Mock<ForeignKeyDefinition>(); var expressionMock = new Mock<DeleteForeignKeyExpression>(); expressionMock.SetupGet(e => e.ForeignKey).Returns(foreignKeyMock.Object); var builder = new DeleteForeignKeyExpressionBuilder(expressionMock.Object); ((IDeleteForeignKeyOnTableSyntax)builder).OnTable(("Bacon")); foreignKeyMock.VerifySet(f => f.ForeignTable = "Bacon"); expressionMock.VerifyGet(e => e.ForeignKey); }
public void CanRead_should_call_wrapped_stream( [Values(false, true)] bool canRead) { var mockStream = new Mock<Stream>(); var subject = new BsonStreamAdapter(mockStream.Object); mockStream.SetupGet(s => s.CanRead).Returns(canRead); var result = subject.CanRead; result.Should().Be(canRead); mockStream.VerifyGet(s => s.CanRead, Times.Once); }
public void Create_ArgumentValid_ReturnsTrue() { // ARRANGE var objectUnderTest = new CustomerRepository(); var mockCustomer = new Mock<ICustomer>(); mockCustomer.SetupGet(context => context.firstName).Returns("Eric"); mockCustomer.SetupGet(context => context.lastName).Returns("Brunner"); mockCustomer.SetupGet(context => context.streetAddress).Returns("my street"); mockCustomer.SetupGet(context => context.city).Returns("Vienna"); // ACT var result = objectUnderTest.Create(mockCustomer.Object); // ASSERT Assert.True(result, "Result has an unexpected value"); mockCustomer.VerifyGet(context => context.firstName, Times.Exactly(1)); mockCustomer.VerifyGet(context => context.lastName, Times.Exactly(1)); mockCustomer.VerifyGet(context => context.streetAddress, Times.Exactly(1)); mockCustomer.VerifyGet(context => context.city, Times.Exactly(1)); }
public void CallingColumnAddsDeleteColumnExpressionToContextWithSpecifiedName() { var collectionMock = new Mock<ICollection<IMigrationExpression>>(); var contextMock = new Mock<IMigrationContext>(); contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object); var root = new DeleteExpressionRoot(contextMock.Object); root.Column("Bacon"); collectionMock.Verify(x => x.Add(It.Is<DeleteColumnExpression>(e => e.ColumnName.Equals("Bacon")))); contextMock.VerifyGet(x => x.Expressions); }
public void CallingIntoTableSetsTableName() { var collectionMock = new Mock<ICollection<IMigrationExpression>>(); var contextMock = new Mock<IMigrationContext>(); contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object); var root = new InsertExpressionRoot(contextMock.Object); root.IntoTable("Bacon"); collectionMock.Verify(x => x.Add(It.Is<InsertDataExpression>(e => e.TableName.Equals("Bacon")))); contextMock.VerifyGet(x => x.Expressions); }
public void CallingFromTableSetsForeignTableName() { var foreignKeyMock = new Mock<ForeignKeyDefinition>(); var expressionMock = new Mock<CreateForeignKeyExpression>(); expressionMock.SetupGet(e => e.ForeignKey).Returns(foreignKeyMock.Object); var builder = new CreateForeignKeyExpressionBuilder(expressionMock.Object); builder.FromTable("Bacon"); foreignKeyMock.VerifySet(f => f.ForeignTable = "Bacon"); expressionMock.VerifyGet(e => e.ForeignKey); }
public void CallingForeignKeyAddsDeleteForeignKeyExpressionToContext() { var collectionMock = new Mock<ICollection<IMigrationExpression>>(); var contextMock = new Mock<IMigrationContext>(); contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object); var root = new DeleteExpressionRoot(contextMock.Object); root.ForeignKey(); collectionMock.Verify(x => x.Add(It.IsAny<DeleteForeignKeyExpression>())); contextMock.VerifyGet(x => x.Expressions); }
public void CallingForeignKeyAddsCreateForeignKeyExpressionToContextWithSpecifiedNameSet() { var collectionMock = new Mock<ICollection<IMigrationExpression>>(); var contextMock = new Mock<IMigrationContext>(); contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object); var root = new CreateExpressionRoot(contextMock.Object); root.ForeignKey("FK_Bacon"); collectionMock.Verify(x => x.Add(It.Is<CreateForeignKeyExpression>(e => e.ForeignKey.Name.Equals("FK_Bacon")))); contextMock.VerifyGet(x => x.Expressions); }
public void CallingDeleteUniqueConstraintCreatesADeleteConstraintExpression() { var collectionMock = new Mock<ICollection<IMigrationExpression>>(); var contextMock = new Mock<IMigrationContext>(); contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object); var root = new DeleteExpressionRoot(contextMock.Object); root.UniqueConstraint("TestUniqueConstraintName"); collectionMock.Verify(x => x.Add(It.Is<DeleteConstraintExpression>(e => e.Constraint.IsUniqueConstraint == true))); collectionMock.Verify(x => x.Add(It.Is<DeleteConstraintExpression>(e => e.Constraint.ConstraintName == "TestUniqueConstraintName"))); contextMock.VerifyGet(x => x.Expressions); }
public void CallingOnTableSetsTableNameToSpecifiedValue() { var indexMock = new Mock<IndexDefinition>(); var expressionMock = new Mock<CreateIndexExpression>(); expressionMock.SetupGet(e => e.Index).Returns(indexMock.Object); var builder = new CreateIndexExpressionBuilder(expressionMock.Object); builder.OnTable("Bacon"); indexMock.VerifySet(x => x.TableName = "Bacon"); expressionMock.VerifyGet(e => e.Index); }
public void TestCorrectSequenceOfOrdering() { var mockBa = new Mock<BankAccount>(); var mockSi = new Mock<StockItem>(); mockBa.Setup(ba => ba.Balance).Returns(50.0); this._Manager.BankAccounts.Add(mockBa.Object); this._Manager.StockItems.Add(mockSi.Object); this._Manager.OrderItem(mockSi.Object, mockBa.Object, 0); mockBa.VerifyGet(ba => ba.Balance); mockBa.Verify(ba => ba.Transfer(0, 10.0), Times.AtMostOnce()); }
public void MessageTypeIsProbedWhenUnknown() { using (var inputStream = new MemoryStream(Encoding.UTF8.GetBytes("non xml payload"))) { MessageMock.Object.BodyPart.Data = inputStream; MessageMock.Setup(m => m.GetProperty(BtsProperties.OutboundTransportLocation)).Returns("outbound-transport-location"); var probeStreamMock = new Mock <IProbeStream>(); StreamExtensions.StreamProberFactory = stream => probeStreamMock.Object; var sut = new SBMessagingContextPropagator(); sut.Execute(PipelineContextMock.Object, MessageMock.Object); probeStreamMock.VerifyGet(ps => ps.MessageType, Times.Once); } }
public void CallingOnTableSetsTableNameToSpecifiedValue() { var indexMock = new Mock <IndexDefinition>(); var expressionMock = new Mock <CreateIndexExpression>(); expressionMock.SetupGet(e => e.Index).Returns(indexMock.Object); var builder = new CreateIndexExpressionBuilder(expressionMock.Object); builder.OnTable("Bacon"); indexMock.VerifySet(x => x.TableName = "Bacon"); expressionMock.VerifyGet(e => e.Index); }
public void Can_read_write_property() { var value = DateTime.Now; Mock.SetupGet(x => x.Property).Returns(value); Mock.SetupSet(x => x.Property = value); RunQmlTest( "test", @" test.property = test.property "); Mock.VerifyGet(x => x.Property, Times.Once); Mock.VerifySet(x => x.Property = value, Times.Once); }
public void ScrumTeamNames_AllEmpty_ReturnsZeroTeams() { // Arrange var repository = new Mock <IScrumTeamRepository>(MockBehavior.Strict); repository.SetupGet(r => r.ScrumTeamNames).Returns(Enumerable.Empty <string>()); var target = CreatePlanningPokerController(repository: repository.Object); // Act var result = target.ScrumTeamNames; // Verify repository.VerifyGet(r => r.ScrumTeamNames); Assert.IsNotNull(result); CollectionAssert.AreEquivalent(Array.Empty <string>(), result.ToList()); }
public void it_should_build_the_api_documentation_using_a_Shacl_profile() { Mock <ITypeDescriptionBuilder> shaclTypeDescriptionBuilder = SetupTypeDescriptionBuilder(_entityContext, EntityConverter.Shacl); var apiDescriptionBuilder = new ApiDescriptionBuilder <TestController>( _descriptionBuilder, _xmlDocProvider.Object, new[] { _typeDescriptionBuilder.Object, shaclTypeDescriptionBuilder.Object }, new IServerBehaviorAttributeVisitor[0], _namedGraphSelectorFactory.Object); apiDescriptionBuilder.BuildDescription(_apiDocumentation.Object, new[] { EntityConverter.Shacl }); _typeDescriptionBuilder.VerifyGet(instance => instance.SupportedProfiles, Times.Once); shaclTypeDescriptionBuilder.VerifyGet(instance => instance.SupportedProfiles, Times.Once); _typeDescriptionBuilder.Verify(instance => instance.BuildTypeDescription(It.IsAny <DescriptionContext>()), Times.Never); }
public void DraggingUnsupportedFilesDoesNothing() { // Arrange var vm = new ComposeTweetViewModel(null); var dropInfo = new Mock <IDropInfo>(); dropInfo.SetupGet(d => d.Data).Returns(new DataObject(DataFormats.FileDrop, new[] { "file1.txt", "file2.exe" })); dropInfo.SetupSet(d => d.Effects = DragDropEffects.Copy).Verifiable(); // Act vm.DragOver(dropInfo.Object); // Assert dropInfo.VerifyGet(d => d.Data, Times.Once()); dropInfo.VerifySet(d => d.Effects = DragDropEffects.Copy, Times.Never()); }
public void CheckLicenseKeyForLowIncomeApplications() { var mockValidator = new Mock <IFrequentFlyerNumberValidator>(); mockValidator.Setup(x => x.ServiceInformation.License.LicenseKey).Returns("OK"); var sut = new CreditCardApplicationEvaluator(mockValidator.Object); var application = new CreditCardApplication { GrossAnnualIncome = 99_000 }; sut.Evaluate(application); mockValidator.VerifyGet(x => x.ServiceInformation.License.LicenseKey, Times.Once); }
public void Can_get_and_set_byte_array() { Mock.SetupGet(x => x.Array).Returns(new byte[] { 3, 5 }); RunQmlTest( "test", @" var v = test.array var data = new Uint8Array(v) data.set([4], 0) test.array = v "); Mock.VerifyGet(x => x.Array, Times.Once); Mock.VerifySet(x => x.Array = new byte[] { 4, 5 }); }
public void CallingDeleteUniqueConstraintCreatesADeleteConstraintExpression() { var collectionMock = new Mock <ICollection <IMigrationExpression> >(); var contextMock = new Mock <IMigrationContext>(); contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object); var root = new DeleteExpressionRoot(contextMock.Object); root.UniqueConstraint("TestUniqueConstraintName"); collectionMock.Verify(x => x.Add(It.Is <DeleteConstraintExpression>(e => e.Constraint.IsUniqueConstraint == true))); collectionMock.Verify(x => x.Add(It.Is <DeleteConstraintExpression>(e => e.Constraint.ConstraintName == "TestUniqueConstraintName"))); contextMock.VerifyGet(x => x.Expressions); }
public void JobLogger_Test_INFO_Only_Console() { // arrange var Mensaje = "Hi!"; var mockConfiguration = new Mock <ILogConfiguration>(); mockConfiguration.Setup(x => x.AllowLevels).Returns(LogLevel.INFO); mockConfiguration.Setup(x => x.AllowSource).Returns(LogSource.CONSOLE); JobLogger.SetLogConfiguration(mockConfiguration.Object); // act JobLogger.Info(Mensaje).Wait(); // assert mockConfiguration.VerifyGet(x => x.AllowLevels); }
public void GetSigningCredentials_ShouldAccessTokenSettingsSecretOnce() { //arrange var appSettings = new Mock <AppSettings> { CallBase = true }; appSettings.SetupGet(i => i.TokenSettings.Secret).Returns("ThisIsATest").Verifiable(); var tokenManager = new TokenManager(Options.Create(appSettings.Object)); //act var result = tokenManager.GetSigningCredentials(); //assert appSettings.VerifyGet(i => i.TokenSettings.Secret, Times.Once); }
public void ConstructorShouldNotAddProvidersWithEmptyMetadataToDictionary() { // Arrange var providerMock = new Mock <IFilterMetadataProvider>(MockBehavior.Strict); providerMock.SetupGet(p => p.Metadata).Returns(new List <FilterMetadata>()); _providers.Add(providerMock.Object); // Act new PredicateFactory(_providersMock.Object); // Assert _providersMock.Verify(m => m.GetEnumerator(), Times.Once); providerMock.VerifyGet(p => p.Metadata, Times.Exactly(2)); }
public void GetSiteTest_NoParameters_None() { var siteServiceMock = new Mock <ISiteService>(); var businessLayer = new GetCmsSiteBusiness() { WriteDebug = Assert.NotNull, WriteVerbose = Assert.NotNull, SiteService = siteServiceMock.Object, }; businessLayer.GetSites().Should().BeEmpty(); siteServiceMock.VerifyGet(x => x.Sites); }
public void ScrumTeamNames_2TeamsInRepository_Returns2Teams() { // Arrange var repository = new Mock <IScrumTeamRepository>(MockBehavior.Strict); repository.SetupGet(r => r.ScrumTeamNames).Returns(new string[] { "team1", "team2" }); var target = CreatePlanningPokerController(repository: repository.Object); // Act var result = target.ScrumTeamNames; // Verify repository.VerifyGet(r => r.ScrumTeamNames); Assert.IsNotNull(result); CollectionAssert.AreEquivalent(new string[] { "team1", "team2" }, result.ToList()); }
public void Stop_Client_Without_Start_First_OK() { var tcpclientmock = new Mock <ITcpClient>(); tcpclientmock.SetupGet(c => c.IsConnected).Returns(() => false); var client = new NikoClient(tcpclientmock.Object); client.StopClient(); client.Should().NotBeNull(); tcpclientmock.Verify(c => c.Start(), Times.Never); tcpclientmock.Verify(c => c.Stop(), Times.Never); tcpclientmock.VerifyGet(c => c.IsConnected, Times.Once); client.IsConnected.Should().BeFalse(); }
public void the_workstation_id_should_be_used() { //Arrange var mockCustomerRepository = new Mock <ICustomerRepository>(); var mockApplicationSettings = new Mock <IApplicationSettings>(); mockApplicationSettings.Setup(x => x.WorkstationId).Returns(123); var customerService = new CustomerService(mockCustomerRepository.Object, mockApplicationSettings.Object); //Act customerService.Create(new CustomerToCreateDto()); //Assert mockApplicationSettings.VerifyGet(x => x.WorkstationId); }
public void RepositoryPropertyCallOnce() { var mock = new Mock <IRepository>(); mock.SetupGet(m => m.Products).Returns(new[] { new Product { Name = "P1", Price = 100M } }); var controller = new HomeController { Repository = mock.Object }; var result = controller.Index(); mock.VerifyGet(m => m.Products, Times.Once); }
public void DraggingNonFileContentDoesNothing() { // Arrange var vm = new ComposeTweetViewModel(null); var dropInfo = new Mock <IDropInfo>(); dropInfo.SetupGet(d => d.Data).Returns(new DataObject()); dropInfo.SetupSet(d => d.Effects = DragDropEffects.Copy).Verifiable(); // Act vm.DragOver(dropInfo.Object); // Assert dropInfo.VerifyGet(d => d.Data, Times.Once()); dropInfo.VerifySet(d => d.Effects = DragDropEffects.Copy, Times.Never()); }
public async Task SendAsync_HostInErrorState_Returns503Immediately() { _managerMock.SetupGet(p => p.State).Returns(ScriptHostState.Error); _managerMock.SetupGet(p => p.LastError).Returns(new Exception()); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://functions.test.com/api/test"); var ex = await Assert.ThrowsAsync <HttpResponseException>(async() => { await _invoker.SendAsync(request, CancellationToken.None); }); HttpResponseMessage response = ex.Response; Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode); _managerMock.VerifyGet(p => p.State, Times.Exactly(5)); }
public void AddProduct_Always_AddedSuccessfully() { // arrange var mock = new Mock <IDatabase>(); var productsList = new List <Product>(); mock.Setup(repo => repo.Products).Returns(productsList); var repository = new Repository(mock.Object); // act repository.AddProduct("Box", 10); // assert mock.VerifyGet(x => x.Products); productsList.Should().HaveCount(1).And.BeEquivalentTo(new Product(1, "Box", 10)); }
public async Task WorkItemManager_Create_DoNotCreateWithoutProperties() { // arrange var providerMock = new Mock <IDataProvider>(); providerMock.SetupGet(o => o.Write).Returns(true); var manager = new WorkItemManager(providerMock.Object, new CommonSdlcDescriptorProvider()); // act var result = await manager.CreateAsync("FOO", "BAR", new Property[] { }); // assert Assert.False(result.Success); providerMock.VerifyGet(o => o.Write); providerMock.VerifyNoOtherCalls(); }
public async Task GetStatus() { var audioEngine = new Mock <IAudioEngine>(); var settingsService = new Mock <ISettingsService>(); audioEngine.SetupGet(x => x.IsRunning).Returns(true); var processor = new EngineProcessor(audioEngine.Object, settingsService.Object); var result = await processor.ProcessAsync("getstatus", null).ConfigureAwait(false); audioEngine.VerifyGet(e => e.IsRunning, Times.Once); Assert.NotNull(result); Assert.True(result.IsSuccess); }
public void the_workstationid_should_be_retrieved() { //Arrange var mockCustomerRepository = new Mock <ICustomerRepository>(); var mockApplicationSettings = new Mock <IApplicationSettings>(); var customerService = new CustomerService(mockCustomerRepository.Object, mockApplicationSettings.Object); //Act customerService.Create(new CustomerToCreateDto()); //Assert mockApplicationSettings.VerifyGet( x => x.SystemConfiguration.AuditingInformation.WorkstationId); }
public void ChannelEventReceived_Rssi_TriggersRssiEvent() { // Setup var routeEventArgs = new RouteMyoEventArgs( new IntPtr(123), new IntPtr(789), MyoEventType.Rssi, DateTime.UtcNow); var channelListener = new Mock <IChannelListener>(MockBehavior.Strict); var myoDeviceDriver = new Mock <IMyoDeviceDriver>(MockBehavior.Strict); myoDeviceDriver .SetupGet(x => x.Handle) .Returns(new IntPtr(123)); myoDeviceDriver .Setup(x => x.GetEventRssi(routeEventArgs.Event)) .Returns(123); var myo = Myo.Create( channelListener.Object, myoDeviceDriver.Object); RssiEventArgs actualEventArgs = null; object actualSender = null; myo.Rssi += (sender, args) => { actualSender = sender; actualEventArgs = args; }; // Execute channelListener.Raise( x => x.EventReceived += null, routeEventArgs); // Assert Assert.Equal(myo, actualSender); Assert.Equal(myo, actualEventArgs.Myo); Assert.Equal(routeEventArgs.Timestamp, actualEventArgs.Timestamp); Assert.Equal(123, actualEventArgs.Rssi); myoDeviceDriver.VerifyGet(x => x.Handle, Times.Once); myoDeviceDriver.Verify(x => x.GetEventRssi(routeEventArgs.Event), Times.Once); }
public async Task ValidationCacheService_GetValidKeyWithListWithTwoValues_ShouldReturnANewCopyOfTheLastUpdatedOne() { // Arrange string key = "some key"; var now = DateTime.Now; var value1Mock = new Mock <IValidationCacheEntity>(); value1Mock .SetupGet(v => v.LastUpdate) .Returns(now); var value2Mock = new Mock <IValidationCacheEntity>(); value2Mock .SetupGet(v => v.LastUpdate) .Returns(now + TimeSpan.FromHours(1)); var expectedValue = value2Mock.Object; var list = new IValidationCacheEntity[] { value1Mock.Object, value2Mock.Object }; var repositoryMock = new Mock <IValidationCacheDataRepository>(); repositoryMock .Setup(r => r.GetAll(key)) .Returns(list); var dateTimeProviderMock = new Mock <IDateTimeProvider>(); var service = new ValidationCacheService(repositoryMock.Object, dateTimeProviderMock.Object); // Act var result = await service.Get(key); // Asset Assert.IsNotNull(result); Assert.AreNotSame(value1Mock.Object, result); Assert.AreNotSame(value2Mock.Object, result); Assert.AreEqual(expectedValue.Content, result.Content); Assert.AreEqual(expectedValue.LastUpdate, result.LastUpdate); Assert.AreEqual(expectedValue.Status, result.Status); repositoryMock.Verify(r => r.GetAll(key), Times.Once); dateTimeProviderMock.VerifyGet(p => p.Now, Times.Never); }
public async Task CallCorrectServiceMethod() { //Arrange const string uID = "213123"; const string pass = "******"; var user = new User { Id = uID }; var userManagerMock = new Mock <IUserManager <User> >(); var passwordValidatorMock = new Mock <IPasswordValidator <User> >(); var passwordValidatorMock2 = new Mock <IPasswordValidator <User> >(); passwordValidatorMock .Setup(pvm => pvm.ValidateAsync(It.IsAny <UserManager <User> >(), user, pass)) .ReturnsAsync(IdentityResult.Success); passwordValidatorMock2 .Setup(pvm => pvm.ValidateAsync(It.IsAny <UserManager <User> >(), user, pass)) .ReturnsAsync(IdentityResult.Success); userManagerMock .SetupGet(umm => umm.Users) .Returns(new List <User> { user }.AsQueryable()); userManagerMock .SetupGet(umm => umm.PasswordValidators) .Returns(new List <IPasswordValidator <User> > { passwordValidatorMock.Object, passwordValidatorMock2.Object }); userManagerMock .Setup(umm => umm.RemovePasswordAsync(It.IsAny <User>())) .ReturnsAsync(IdentityResult.Success); userManagerMock .Setup(umm => umm.AddPasswordAsync(It.IsAny <User>(), pass)) .ReturnsAsync(IdentityResult.Success); var sut = new UsersController(userManagerMock.Object); //Act var result = await sut.ChangePassword(new UserModalModelView { ID = uID, ConfirmPassword = pass, NewPassword = pass }) as RedirectToActionResult; //Assert userManagerMock.Verify(umm => umm.Users, Times.Once); userManagerMock.VerifyGet(umm => umm.PasswordValidators, Times.Once); passwordValidatorMock.Verify(pvm => pvm.ValidateAsync(It.IsAny <UserManager <User> >(), user, pass), Times.Once); passwordValidatorMock2.Verify(pvm => pvm.ValidateAsync(It.IsAny <UserManager <User> >(), user, pass), Times.Once); userManagerMock.Verify(s => s.RemovePasswordAsync(user), Times.Once); userManagerMock.Verify(s => s.AddPasswordAsync(user, pass), Times.Once); }
public void Accept() { LoanProduct product = new LoanProduct(99, "Loan", 5.25m); LoanAmount amount = new LoanAmount("USD", 200_000); var application = new LoanApplication(42, product, amount, "Sarah", 25, "133 Pluralsight Drive, Draper, Utah", 65_000); // setting up a mock method return var mockIdentityVerifier = new Mock <IIdentityVerifier>(); mockIdentityVerifier.Setup(x => x.Validate(It.IsAny <string>(), It.IsAny <int>(), "133 Pluralsight Drive, Draper, Utah")).Returns(true); // setting up a mock property var mockCreditScorer = new Mock <ICreditScorer>(); mockCreditScorer.Setup(x => x.Score).Returns(300); // manully setting up a mock property hierarchy // CreditScorer -> ScoreResult -> ScoreValue //var mockScoreValue = new Mock<ScoreValue>(); //mockScoreValue.Setup(x => x.Score).Returns(300); //var mockScoreResult = new Mock<ScoreResult>(); //mockScoreResult.Setup(x => x.ScoreValue).Returns(mockScoreValue.Object); //mockCreditScorer.Setup(x => x.ScoreResult).Returns(mockScoreResult.Object); // Getting moq to create the hierarchy of object // Moq creates each of the objects in the hierarchy, all the properties in hierarchy must be virtual mockCreditScorer.Setup(x => x.ScoreResult.ScoreValue.Score).Returns(300); // Tracking changes to properties // Can provide an initial value with a second argument mockCreditScorer.SetupProperty(x => x.Count); // Can use the below to setup all properties but it will overwrite any previous setup, so use it first! //mockCreditScorer.SetupAllProperties(); var sut = new LoanApplicationProcessor(mockIdentityVerifier.Object, mockCreditScorer.Object); sut.Process(application); // Check property was accessed, number of times is optional mockCreditScorer.VerifyGet(x => x.ScoreResult.ScoreValue.Score, Times.Once); // Check property was set mockCreditScorer.VerifySet(x => x.Count = It.IsAny <int>()); Assert.That(application.GetIsAccepted(), Is.True); Assert.That(mockCreditScorer.Object.Count, Is.EqualTo(1)); }
public void AddGameAchievements() { const int gameId = 99; List <Achievement> gameAchievements = new List <Achievement>(); for (int i = 0; i < 10; i++) { Achievement achievement = new Achievement { ImageUrl = "http://example.com/achievement" + i + ".gif", ApiName = i.ToString(), AchievementNames = new EntitySet <AchievementName> { new AchievementName { Name = "Achievement " + i, Description = "Achievement " + i } } }; gameAchievements.Add(achievement); } _repositoryMock.SetupGet(rep => rep.Achievements).Returns(_achievements); _manager.AddAchievements(99, gameAchievements); _repositoryMock.VerifyGet(rep => rep.Achievements); _repositoryMock.Verify(rep => rep.InsertOnSubmit(It.IsAny <Achievement>()), Times.Exactly(gameAchievements.Count)); _repositoryMock.Verify(rep => rep.SubmitChanges()); List <Achievement> expectedAchievements = new List <Achievement>(_achievements); expectedAchievements.AddRange(gameAchievements); _repositoryMock.SetupGet(rep => rep.Achievements).Returns(expectedAchievements.AsQueryable()); Assert.That(_repositoryMock.Object.Achievements.Count(a => a.GameId == gameId), Is.EqualTo(10)); }
public void CallingColumnAddsAlterColumnExpressionToContextWithSpecifiedNameSet() { var collectionMock = new Mock <ICollection <IMigrationExpression> >(); var contextMock = new Mock <IMigrationContext>(); contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object); var root = new AlterExpressionRoot(contextMock.Object); root.Column("Bacon"); collectionMock.Verify(x => x.Add(It.Is <AlterColumnExpression>(e => e.Column.Name.Equals("Bacon")))); contextMock.VerifyGet(x => x.Expressions); }
public void JenkinsLookup2_Implementation_Constructor_Config_IsCloned() { var jenkinsLookupConfigMock = new Mock <IJenkinsLookup2Config>(); { jenkinsLookupConfigMock.Setup(jlc => jlc.Clone()) .Returns(() => new JenkinsLookup2Config()); } GC.KeepAlive( new JenkinsLookup2_Implementation(jenkinsLookupConfigMock.Object)); jenkinsLookupConfigMock.Verify(jlc => jlc.Clone(), Times.Once); jenkinsLookupConfigMock.VerifyGet(jlc => jlc.Seed, Times.Never); }