public void ImportEncounterFromVisit_BillingOfficeExistsAndCodingContextHasProceduresAndVisitHasProblems_SynchronizeEncounterCorrectly() { // Setup var fixture = new Fixture().Customize(new AutoMoqCustomization()); var billingOffice = new Mock <BillingOffice>(); var billingOfficeRepository = new Mock <IBillingOfficeRepository>(); billingOfficeRepository.Setup(p => p.GetByAgencyKey(It.IsAny <long>())).Returns(billingOffice.Object); fixture.Register(() => billingOfficeRepository.Object); var patientAccount = new Mock <PatientAccount>(); var patientAccountSynchronizationService = new Mock <IPatientAccountSynchronizationService>(); patientAccountSynchronizationService.Setup(p => p.SynchronizePatientAccount(It.IsAny <Patient>())).Returns(patientAccount.Object); fixture.Register(() => patientAccountSynchronizationService.Object); var patient = new Mock <Patient>(); var agency = new Mock <Agency>(); patient.Setup(p => p.Agency).Returns(agency.Object); var diagnosisCodedConcept = fixture.CreateAnonymous <CodedConcept>(); var problem = new Mock <Problem> (); problem.SetupGet(p => p.ProblemCodeCodedConcept).Returns(diagnosisCodedConcept); var visitProblem = new Mock <VisitProblem> (); visitProblem.SetupGet(p => p.Problem).Returns(problem.Object); var visit = new Mock <Visit>(); visit.SetupGet(p => p.Problems).Returns(new List <VisitProblem> { visitProblem.Object }); visit.Setup(v => v.ClinicalCase.Patient).Returns(patient.Object); var visitRepository = new Mock <IVisitRepository>(); visitRepository.Setup(p => p.GetByKey((It.IsAny <long>()))).Returns(visit.Object); fixture.Register(() => visitRepository.Object); var claimBatch = new Mock <ClaimBatch> (); var claim = new Mock <Claim> (); claim.Setup(p => p.AssignClaimBatch()).Returns(() => claimBatch.Object); var encounter = new Mock <Encounter> (); encounter.Setup(p => p.GenerateClaim()).Returns(claim.Object); var encounterSynchronizationService = new Mock <IEncounterSynchronizationService>(); encounterSynchronizationService.Setup(p => p.SynchronizeEncounter(It.IsAny <PatientAccount>(), visit.Object)).Returns(encounter.Object); fixture.Register(() => encounterSynchronizationService); var procedureOne = new Mock <Procedure> (); var procedureTwo = new Mock <Procedure> (); var procedures = new List <Procedure> { procedureOne.Object, procedureTwo.Object }; var codingContext = new Mock <CodingContext>(); codingContext.SetupGet(p => p.Procedures).Returns(() => procedures); var codeContextRepository = new Mock <ICodingContextRepository>(); codeContextRepository.Setup(p => p.GetByVisitKey(It.IsAny <long>())).Returns(codingContext.Object); fixture.Register(() => codeContextRepository.Object); var serviceSynchronizationService = new Mock <IServiceSynchronizationService> (); fixture.Register(() => serviceSynchronizationService.Object); var visitImportService = fixture.CreateAnonymous <VisitImportService>(); // Exercise visitImportService.ImportVisit(fixture.CreateAnonymous <long>()); // Verify serviceSynchronizationService.Verify(p => p.SynchronizeService(encounter.Object, It.IsAny <Procedure>(), diagnosisCodedConcept), Times.Exactly(2)); serviceSynchronizationService.Verify(p => p.SynchronizeService(encounter.Object, procedureOne.Object, diagnosisCodedConcept), Times.Exactly(1)); serviceSynchronizationService.Verify(p => p.SynchronizeService(encounter.Object, procedureOne.Object, diagnosisCodedConcept), Times.Exactly(1)); }
public async Task Post_AddsConnectionsAndCallsEmailServiceAsync() { var addedConnections = new List <connection_user_topic>(); var removedConnections = new List <connection_user_topic>(); var postDto = SetupForPost(addedConnections); var toSubscribe = new List <int> { 1, 2 }; postDto.To_Subscribe = toSubscribe; var topicsController = new TopicsController(unitOfWork.Object, mockEmailService.Object, mockManager.Object); await topicsController.PostControllerAsync(postDto); Assert.AreEqual(toSubscribe.Count, addedConnections.Count); Assert.AreEqual(toSubscribe[0], addedConnections[0].TopicID); Assert.AreEqual(toSubscribe[1], addedConnections[1].TopicID); Assert.AreEqual(user.Id, addedConnections[0].AspNetUserID); mockEmailService.Verify(x => x.SendNecessaryArticlesToUser(It.IsAny <AspNetUser>(), It.IsAny <int>()), Times.Exactly(toSubscribe.Count)); }
public void VerifyListByAuthorIdCalled(int timesCalled) { _mockIBlogPostDataAccessAdapter .Verify(x => x.ListByAuthorId(It.IsAny <Guid>()), Times.Exactly(timesCalled)); }
public void PerformanceCounterBuilder_CtorBuildCounters_NewResets_ExpectNewCounters() { try { PerformanceCounterCategory.Delete(CategoryName); } catch { } var mockCounterFactory = new Mock <PerformanceCounters.Counters.IRealPerformanceCounterFactory>(); var mockCounter1 = new Mock <IWarewolfPerformanceCounter>(); var mockCounter2 = new Mock <IWarewolfPerformanceCounter>(); var mockCounter3 = new Mock <IWarewolfPerformanceCounter>(); var mockCounter4 = new Mock <IWarewolfPerformanceCounter>(); var mockCounter5 = new Mock <IWarewolfPerformanceCounter>(); var mockCounter6 = new Mock <IWarewolfPerformanceCounter>(); mockCounterFactory.Setup(o => o.New(GlobalConstants.Warewolf, "Concurrent requests currently executing", GlobalConstants.GlobalCounterName)).Returns(mockCounter1.Object).Verifiable(); mockCounterFactory.Setup(o => o.New(GlobalConstants.Warewolf, "Total Errors", GlobalConstants.GlobalCounterName)).Returns(mockCounter2.Object).Verifiable(); mockCounterFactory.Setup(o => o.New(GlobalConstants.Warewolf, "Request Per Second", GlobalConstants.GlobalCounterName)).Returns(mockCounter3.Object).Verifiable(); mockCounterFactory.Setup(o => o.New(GlobalConstants.Warewolf, "Average workflow execution time", GlobalConstants.GlobalCounterName)).Returns(mockCounter4.Object).Verifiable(); mockCounterFactory.Setup(o => o.New(GlobalConstants.Warewolf, "average time per operation base", GlobalConstants.GlobalCounterName)).Returns(mockCounter5.Object).Verifiable(); mockCounterFactory.Setup(o => o.New(GlobalConstants.Warewolf, "Count of Not Authorised errors", GlobalConstants.GlobalCounterName)).Returns(mockCounter6.Object).Verifiable(); var counterFactory = mockCounterFactory.Object; var lst = new List <IPerformanceCounter> { new WarewolfCurrentExecutionsPerformanceCounter(counterFactory), new WarewolfNumberOfErrors(counterFactory), new WarewolfRequestsPerSecondPerformanceCounter(counterFactory), new WarewolfAverageExecutionTimePerformanceCounter(counterFactory), new WarewolfNumberOfAuthErrors(counterFactory) }; var mockPerformanceCounterCategory = new Mock <IPerformanceCounterCategory>(); { int expectedCount = 5; mockPerformanceCounterCategory.Setup(o => o.Create("Warewolf", "Warewolf Performance Counters", It.IsAny <IEnumerable <IPerformanceCounter> >())) .Callback <string, string, IEnumerable <IPerformanceCounter> >((s1, s2, counters_arg) => Assert.AreEqual(expectedCount++, counters_arg.Count())).Verifiable(); } mockPerformanceCounterCategory.Setup(o => o.Create("Warewolf Services", "Warewolf Performance Counters", It.IsAny <IEnumerable <IPerformanceCounter> >())) .Callback <string, string, IEnumerable <IPerformanceCounter> >((s1, s2, counters_arg) => Assert.AreEqual(0, counters_arg.Count())).Verifiable(); var register = new WarewolfPerformanceCounterRegister(mockPerformanceCounterCategory.Object, lst, new List <IResourcePerformanceCounter>()); foreach (var performanceCounter in register.Counters) { performanceCounter.ToSafe().Increment(); } mockPerformanceCounterCategory.Verify(); mockCounterFactory.Verify(o => o.New(GlobalConstants.Warewolf, "Concurrent requests currently executing", GlobalConstants.GlobalCounterName), Times.Once); mockCounterFactory.Verify(o => o.New(GlobalConstants.Warewolf, "Total Errors", GlobalConstants.GlobalCounterName), Times.Once); mockCounterFactory.Verify(o => o.New(GlobalConstants.Warewolf, "Request Per Second", GlobalConstants.GlobalCounterName), Times.Once); mockCounterFactory.Verify(o => o.New(GlobalConstants.Warewolf, "Average workflow execution time", GlobalConstants.GlobalCounterName), Times.Once); mockCounterFactory.Verify(o => o.New(GlobalConstants.Warewolf, "average time per operation base", GlobalConstants.GlobalCounterName), Times.Once); mockCounterFactory.Verify(o => o.New(GlobalConstants.Warewolf, "Count of Not Authorised errors", GlobalConstants.GlobalCounterName), Times.Once); mockCounter1.Verify(o => o.Increment(), Times.Once); mockCounter2.Verify(o => o.Increment(), Times.Once); mockCounter3.Verify(o => o.Increment(), Times.Once); mockCounter4.Verify(o => o.Increment(), Times.Once); mockCounter5.Verify(o => o.Increment(), Times.Once); mockCounter6.Verify(o => o.Increment(), Times.Once); var mockCounter7 = new Mock <IWarewolfPerformanceCounter>(); mockCounterFactory.Setup(o => o.New(GlobalConstants.Warewolf, "Count of requests for workflows which don't exist", GlobalConstants.GlobalCounterName)).Returns(mockCounter7.Object); lst.Add(new WarewolfServicesNotFoundCounter(counterFactory)); register = new WarewolfPerformanceCounterRegister(mockPerformanceCounterCategory.Object, lst, new List <IResourcePerformanceCounter>()); foreach (var performanceCounter in register.Counters) { performanceCounter.ToSafe().Increment(); // increment causes instance to be created on windows side } mockCounterFactory.Verify(o => o.New(GlobalConstants.Warewolf, "Count of requests for workflows which don't exist", GlobalConstants.GlobalCounterName), Times.Once); mockCounter1.Verify(o => o.Increment(), Times.Exactly(2)); mockCounter2.Verify(o => o.Increment(), Times.Exactly(2)); mockCounter3.Verify(o => o.Increment(), Times.Exactly(2)); mockCounter4.Verify(o => o.Increment(), Times.Exactly(2)); mockCounter5.Verify(o => o.Increment(), Times.Exactly(2)); mockCounter6.Verify(o => o.Increment(), Times.Exactly(2)); mockCounter7.Verify(o => o.Increment(), Times.Once); }
public void UpdateAsync_Success_WhenNoCondition(bool isNear) { _pathManagerMock.SetupGet(manager => manager.LastWaypoint).Returns(new Path.Waypoint()); _stuckManagerMock.SetupGet(manager => manager.IsStuck).Returns(false); _pathManagerMock.Setup(manager => manager.IsNear(It.IsAny <Path.Waypoint>())).Returns(isNear); var resultTask = _movementHandler.UpdateAsync(); Assert.Equal(Task.CompletedTask, resultTask); _pathManagerMock.Verify(manager => manager.LastWaypoint, isNear ? Times.Exactly((2)) : Times.Exactly(3)); _stuckManagerMock.Verify(manager => manager.IsStuck, Times.Once); _pathManagerMock.Verify(manager => manager.IsNear(It.IsAny <Path.Waypoint>()), Times.Once); _pathManagerMock.Verify(manager => manager.SetPosition(It.IsAny <Path.Waypoint>()), Times.Once); if (!isNear) { return; } _pathManagerMock.Verify(manager => manager.NextWaypoint(), Times.Once); _stuckManagerMock.Verify(manager => manager.Toggle(), Times.Once); }
public Task TestRevoke() { var response = new Tuple <HttpStatusCode, IDictionary <string, object> >(HttpStatusCode.Accepted, null); var mockRunner = CreateMockRunner(response); var controller = new ParseSessionController(mockRunner.Object); return(controller.RevokeAsync("S0m3Se551on", CancellationToken.None).ContinueWith(t => { Assert.IsFalse(t.IsFaulted); Assert.IsFalse(t.IsCanceled); mockRunner.Verify(obj => obj.RunCommandAsync(It.Is <ParseCommand>(command => command.Uri.AbsolutePath == "/1/logout"), It.IsAny <IProgress <ParseUploadProgressEventArgs> >(), It.IsAny <IProgress <ParseDownloadProgressEventArgs> >(), It.IsAny <CancellationToken>()), Times.Exactly(1)); })); }
private void AssertSendAsyncWasCalled(int times = 1) { _mockHttpClient .Verify(x => x.UploadData(It.IsAny <Uri>(), "POST", It.IsAny <byte[]>()), Times.Exactly(times)); }
public void ShouldFireRemovedEvents() { var entity = new Entity(); collection.Add(entity); collection.Add(new Entity()); collection.Add(new Entity()); collection.RemovedEntity += mockHandlers.Object.Removed; collection.Remove(entity); collection.Clear(); mockHandlers.Verify(h => h.Removed(It.IsAny <object>(), It.IsAny <EntityEventArgs>()), Times.Exactly(3)); }
public void should_search_for_individual_episodes_when_no_partial_results_are_returned() { Mocker.GetMock <SearchProvider>() .Setup(c => c.PartialSeasonSearch(notification, 1, 1)).Returns(new List <int>()); Mocker.Resolve <SeasonSearchJob>().Start(notification, new { SeriesId = 1, SeasonNumber = 1 }); Mocker.GetMock <EpisodeSearchJob>().Verify(v => v.Start(notification, It.Is <object>(o => o.GetPropertyValue <Int32>("EpisodeId") > 0)), Times.Exactly(_episodes.Count)); }
public async Task AdicionarItem_CommandInvalido_DeveRetornarFalsoELancarEventosDeNotificacao() { // Arrange var pedidoCommand = new AdicionarItemPedidoCommand(Guid.Empty, Guid.Empty, "", 0, 0); // Act var result = await _pedidoHandler.Handle(pedidoCommand, CancellationToken.None); // Assert Assert.False(result); _mocker.GetMock <IMediator>().Verify(m => m.Publish(It.IsAny <INotification>(), CancellationToken.None), Times.Exactly(5)); }
public async Task Save_ForDeletedDiscWithVariousDeleteCommentWhenDeleteCommentWasChanged_UpdatesDiscCorrectly() { // Arrange var songs = new[] { new SongModel { DeleteDate = new DateTime(2021, 10, 25), DeleteComment = "Old Delete Comment 1" }, new SongModel { DeleteDate = new DateTime(2021, 10, 25), DeleteComment = "Old Delete Comment 2" }, }; var disc = new DiscModel { Title = "Old Title", TreeTitle = "Old Tree Title", AlbumTitle = "Old Album Title", Year = 2021, }; disc.AddSongs(songs); var mocker = new AutoMocker(); var target = mocker.CreateInstance <EditDiscPropertiesViewModel>(); target.Load(disc); // Act target.Title = "New Title"; target.TreeTitle = "New Tree Title"; target.AlbumTitle = "New Album Title"; target.DeleteComment = "New Delete Comment"; target.Year = 2021; await target.Save(CancellationToken.None); // Assert Func <Action <DiscModel>, bool> verifyDiscUpdate = updateAction => { updateAction(disc); return(disc.Title == "New Title" && disc.TreeTitle == "New Tree Title" && disc.AlbumTitle == "New Album Title" && disc.Year == 2021); }; var discServiceMock = mocker.GetMock <IDiscsService>(); discServiceMock.Verify(x => x.UpdateDisc(disc, It.Is <Action <DiscModel> >(y => verifyDiscUpdate(y)), It.IsAny <CancellationToken>()), Times.Once); Func <SongModel, Action <SongModel>, bool> verifySongUpdate = (song, updateAction) => { updateAction(song); return(song.DeleteComment == "New Delete Comment"); }; var songServiceMock = mocker.GetMock <ISongsService>(); songServiceMock.Verify(x => x.UpdateSong(It.IsAny <SongModel>(), It.IsAny <Action <SongModel> >(), It.IsAny <CancellationToken>()), Times.Exactly(2)); songServiceMock.Verify(x => x.UpdateSong(songs[0], It.Is <Action <SongModel> >(y => verifySongUpdate(songs[0], y)), It.IsAny <CancellationToken>()), Times.Once); songServiceMock.Verify(x => x.UpdateSong(songs[1], It.Is <Action <SongModel> >(y => verifySongUpdate(songs[1], y)), It.IsAny <CancellationToken>()), Times.Once); }
public void RescanCommand_ShouldSetAlotOfProperties() { _sut.ReScanCommand.Execute(null); Assert.That(_sut.ScannedUsers, Is.Not.Empty); Assert.That(_sut.ScannedMeals, Is.Not.Empty); Assert.That(_sut.FilterdScannedMeals.Count, Is.EqualTo(1)); Assert.That(_sut.ScannedMeal, Is.EqualTo(meal1)); Assert.That(_sut.ScannedPerson, Is.EqualTo(user)); _menuServiceMock.Verify(service => service.GetLastMenu(), Times.Exactly(2)); _mealDataServiceMock.Verify(service => service.GetMealById(It.IsAny <long>()), Times.Exactly(2)); _userServiceMock.Verify(service => service.GetUserById(It.IsAny <int>()), Times.Exactly(2)); }
public void GetTestResults_OutputWithInvalidDurationUnit_DefaultDurationIsUsedAndWarningIsProduced() { List <TestResult> results = ComputeTestResults(WrongDurationUnit); results.Count.Should().Be(1); results[0].TestCase.FullyQualifiedName.Should().Be("TestMath.AddFails"); results[0].Duration.Should().Be(TimeSpan.FromMilliseconds(1)); results[0].ErrorStackTrace.Should().Contain(@"c:\users\chris\documents\visual studio 2015\projects\consoleapplication1\consoleapplication1tests\source.cpp"); MockLogger.Verify(l => l.LogWarning( It.Is <string>(s => s.Contains("'[ FAILED ] TestMath.AddFails (3 s)'"))), Times.Exactly(1)); }
public void ImportEncounterFromVisit_BillingOfficeExists_SynchronizePatientAccountCorrectly() { // Setup var fixture = new Fixture().Customize(new AutoMoqCustomization()); var billingOffice = new Mock <BillingOffice> (); var billingOfficeRepository = new Mock <IBillingOfficeRepository>(); billingOfficeRepository.Setup(p => p.GetByAgencyKey(It.IsAny <long>())).Returns(billingOffice.Object); fixture.Register(() => billingOfficeRepository.Object); var patientAccountSynchronizationService = new Mock <IPatientAccountSynchronizationService> (); fixture.Register(() => patientAccountSynchronizationService.Object); var patient = new Mock <Patient>(); var agency = new Mock <Agency>(); patient.Setup(p => p.Agency).Returns(agency.Object); var visit = new Mock <Visit>(); visit.Setup(v => v.ClinicalCase.Patient).Returns(patient.Object); var visitRepository = new Mock <IVisitRepository>(); visitRepository.Setup(p => p.GetByKey((It.IsAny <long>()))).Returns(visit.Object); fixture.Register(() => visitRepository.Object); var claimBatch = new Mock <ClaimBatch>(); var claim = new Mock <Claim>(); claim.Setup(p => p.AssignClaimBatch()).Returns(() => claimBatch.Object); var encounter = new Mock <Encounter>(); encounter.Setup(p => p.GenerateClaim()).Returns(claim.Object); var encounterSynchronizationService = new Mock <IEncounterSynchronizationService>(); encounterSynchronizationService.Setup(p => p.SynchronizeEncounter(It.IsAny <PatientAccount>(), It.IsAny <Visit>())).Returns( () => encounter.Object); fixture.Register(() => encounterSynchronizationService); var visitImportService = fixture.CreateAnonymous <VisitImportService>(); // Exercise visitImportService.ImportVisit(fixture.CreateAnonymous <long>()); // Verify patientAccountSynchronizationService.Verify(p => p.SynchronizePatientAccount(patient.Object), Times.Exactly(1)); }
public void then_no_exceptions_are_tested_for_transient() { this.detectionStrategyMock.Verify(ds => ds.IsTransient(It.IsAny <Exception>()), Times.Exactly(1)); }
public void should_not_blowup_the_process_due_to_failed_parse() { GivenSpecifications(_pass1); Mocker.GetMock <IAggregationService>() .Setup(c => c.Augment(It.IsAny <LocalMovie>(), It.IsAny <DownloadClientItem>(), It.IsAny <bool>())) .Throws <TestException>(); _videoFiles = new List <string> { "The.Office.S03E115.DVDRip.XviD-OSiTV", "The.Office.S03E115.DVDRip.XviD-OSiTV", "The.Office.S03E115.DVDRip.XviD-OSiTV" }; GivenVideoFiles(_videoFiles); Subject.GetImportDecisions(_videoFiles, _movie); Mocker.GetMock <IAggregationService>() .Verify(c => c.Augment(It.IsAny <LocalMovie>(), It.IsAny <DownloadClientItem>(), It.IsAny <bool>()), Times.Exactly(_videoFiles.Count)); ExceptionVerification.ExpectedErrors(3); }
public async void CanProcessUserMessage() { //Given var user_slack_url = "http://user.slack.url"; var message = $@"*A new buyer has signed up* Name: Foo bar Email: [email protected]"; var logger = new Mock <ILogger <AppService> >(); var config = new Mock <IOptions <AppConfig> >(); config.Setup(ac => ac.Value).Returns(new AppConfig { UserSlackUrl = user_slack_url }); var slackService = new Mock <ISlackService>(); slackService.Setup(ss => ss.SendSlackMessage(user_slack_url, message)).ReturnsAsync(true); var userMessageProcessor = new UserMessageProcessor(logger.Object, config.Object, slackService.Object); //When var awsSnsMessage = new AwsSnsMessage { Message = JsonConvert.SerializeObject(new { user = new { email_address = "*****@*****.**", role = "buyer", name = "Foo bar" } }), MessageAttributes = new MessageAttributes { EventType = new TType { Value = "created" } } }; var result = await userMessageProcessor.Process(awsSnsMessage); //Then slackService.Verify((ss) => ss.SendSlackMessage(user_slack_url, message), Times.Exactly(1)); Assert.True(result, "created should return true"); }
public void StartTestRunShouldCallHandleLogMessageOnTestMessage() { var mockHandler = new Mock <ITestRunEventsHandler>(); var runCriteria = new TestRunCriteriaWithSources(null, null, null); var rawMessage = "OnLogMessage"; var message = new Message() { MessageType = MessageType.TestMessage, Payload = null }; var payload = new TestMessagePayload() { MessageLevel = TestMessageLevel.Error, Message = rawMessage }; this.SetupReceiveRawMessageAsyncAndDeserializeMessageAndInitialize(rawMessage, message); this.mockDataSerializer.Setup(ds => ds.DeserializePayload <TestMessagePayload>(message)).Returns(payload); var completePayload = new TestRunCompletePayload() { ExecutorUris = null, LastRunTests = null, RunAttachments = null, TestRunCompleteArgs = null }; var completeMessage = new Message() { MessageType = MessageType.ExecutionComplete, Payload = null }; var waitHandle = new AutoResetEvent(false); mockHandler.Setup(mh => mh.HandleLogMessage(TestMessageLevel.Error, rawMessage)).Callback( () => { this.mockDataSerializer.Setup(ds => ds.DeserializeMessage(It.IsAny <string>())).Returns(completeMessage); this.mockDataSerializer.Setup(ds => ds.DeserializePayload <TestRunCompletePayload>(completeMessage)).Returns(completePayload); waitHandle.Set(); }); this.testRequestSender.StartTestRun(runCriteria, mockHandler.Object); waitHandle.WaitOne(); this.mockCommunicationManager.Verify(mc => mc.SendMessage(MessageType.StartTestExecutionWithSources, runCriteria), Times.Once); this.mockDataSerializer.Verify(ds => ds.DeserializeMessage(It.IsAny <string>()), Times.Exactly(2)); mockHandler.Verify(mh => mh.HandleLogMessage(payload.MessageLevel, payload.Message), Times.Once); mockHandler.Verify(mh => mh.HandleRawMessage(rawMessage), Times.AtLeastOnce); }
public Task TestUpgradeToRevocableSession() { var response = new Tuple <HttpStatusCode, IDictionary <string, object> >(HttpStatusCode.Accepted, new Dictionary <string, object>() { { "__type", "Object" }, { "className", "Session" }, { "sessionToken", "S0m3Se551on" }, { "restricted", true } }); var mockRunner = CreateMockRunner(response); var controller = new ParseSessionController(mockRunner.Object); return(controller.UpgradeToRevocableSessionAsync("S0m3Se551on", CancellationToken.None).ContinueWith(t => { Assert.IsFalse(t.IsFaulted); Assert.IsFalse(t.IsCanceled); mockRunner.Verify(obj => obj.RunCommandAsync(It.Is <ParseCommand>(command => command.Uri.AbsolutePath == "/1/upgradeToRevocableSession"), It.IsAny <IProgress <ParseUploadProgressEventArgs> >(), It.IsAny <IProgress <ParseDownloadProgressEventArgs> >(), It.IsAny <CancellationToken>()), Times.Exactly(1)); var session = t.Result; Assert.AreEqual(2, session.Count()); Assert.True((bool)session["restricted"]); Assert.AreEqual("S0m3Se551on", session["sessionToken"]); })); }
public void StartTestRunShouldCallLaunchProcessWithDebuggerAndWaitForCallback() { var mockHandler = new Mock <ITestRunEventsHandler>(); var runCriteria = new TestRunCriteriaWithSources(null, null, null); var rawMessage = "LaunchProcessWithDebugger"; var message = new Message() { MessageType = MessageType.LaunchAdapterProcessWithDebuggerAttached, Payload = null }; var payload = new TestProcessStartInfo(); this.SetupReceiveRawMessageAsyncAndDeserializeMessageAndInitialize(rawMessage, message); this.mockDataSerializer.Setup(ds => ds.DeserializePayload <TestProcessStartInfo>(message)).Returns(payload); var completePayload = new TestRunCompletePayload() { ExecutorUris = null, LastRunTests = null, RunAttachments = null, TestRunCompleteArgs = null }; var completeMessage = new Message() { MessageType = MessageType.ExecutionComplete, Payload = null }; mockHandler.Setup(mh => mh.LaunchProcessWithDebuggerAttached(payload)).Callback( () => { this.mockDataSerializer.Setup(ds => ds.DeserializeMessage(It.IsAny <string>())).Returns(completeMessage); this.mockDataSerializer.Setup(ds => ds.DeserializePayload <TestRunCompletePayload>(completeMessage)).Returns(completePayload); }); var waitHandle = new AutoResetEvent(false); mockHandler.Setup(mh => mh.HandleTestRunComplete(It.IsAny <TestRunCompleteEventArgs>(), It.IsAny <TestRunChangedEventArgs>(), It.IsAny <ICollection <AttachmentSet> >(), It.IsAny <ICollection <string> >())).Callback (() => waitHandle.Set()); this.testRequestSender.StartTestRun(runCriteria, mockHandler.Object); waitHandle.WaitOne(); this.mockCommunicationManager.Verify(mc => mc.SendMessage(MessageType.StartTestExecutionWithSources, runCriteria), Times.Once); this.mockDataSerializer.Verify(ds => ds.DeserializeMessage(It.IsAny <string>()), Times.Exactly(2)); mockHandler.Verify(mh => mh.LaunchProcessWithDebuggerAttached(payload), Times.Once); mockHandler.Verify(mh => mh.HandleRawMessage(rawMessage), Times.Exactly(2)); this.mockCommunicationManager.Verify(mc => mc.SendMessage(MessageType.LaunchAdapterProcessWithDebuggerAttachedCallback, It.IsAny <object>()), Times.Once); }
public void CalculateNextGeneration_forNewGrid_works() { var sut = new GameOfLife(new GridSize(10, 10)); // game with 10x10=100 cells on grid var rules = new Mock <IRules>(); rules.Setup(r => r.CalculateNextState(It.IsAny <State>(), It.IsAny <int>())).Returns(State.Alive); sut.NextIteration(rules.Object); //calculateNextState method invoked for every cell rules.Verify(r => r.CalculateNextState(It.IsAny <State>(), It.IsAny <int>()), Times.Exactly(100)); }
public void StartTwice() { // Setup Mock <ISocket> mockSocket = new Mock <ISocket>(); SocketServer socketServer = new SocketServer(); // Act socketServer.Start(mockSocket.Object, 6128); socketServer.Start(mockSocket.Object, 6128); // Verify mockSocket.Verify(s => s.Bind(It.IsAny <System.Net.EndPoint>()), Times.Exactly(2)); mockSocket.Verify(s => s.Listen(1), Times.Exactly(2)); mockSocket.Verify(s => s.BeginAccept(It.IsNotNull <AsyncCallback>(), null), Times.Exactly(2)); mockSocket.Verify(s => s.Close(), Times.Once()); mockSocket.VerifyNoOtherCalls(); }
public void CallMapMethod_WhenCollectionFound() { // Arrange var username = "******"; var model = new EventViewModel(); var mockedIndividualService = new Mock <IIndividualService>(); mockedIndividualService.Setup(x => x.GetCurrentEvents(username)) .Returns(new List <SofiaDayAndNight.Data.Models.Event>() { new SofiaDayAndNight.Data.Models.Event() }); mockedIndividualService.Setup(x => x.GetPassedEvents(username)) .Returns(new List <SofiaDayAndNight.Data.Models.Event>() { new SofiaDayAndNight.Data.Models.Event() }); mockedIndividualService.Setup(x => x.GetUpcomingEvents(username)) .Returns(new List <SofiaDayAndNight.Data.Models.Event>() { new SofiaDayAndNight.Data.Models.Event() }); var mockedOrganizationService = new Mock <IOrganizationService>(); var mockedMapper = new Mock <IMapper>(); mockedMapper.Setup(x => x.Map <EventViewModel>( It.IsAny <SofiaDayAndNight.Data.Models.Event>())) .Returns(model); var mockedPhotoHelper = new Mock <IPhotoHelper>(); var mockedUserProvider = new Mock <IUserProvider>(); //var principal = new Mock<IPrincipal>(); //var controllerContext = new Mock<ControllerContext>(); //principal.SetupGet(x => x.Identity.Name).Returns(username); //controllerContext.SetupGet(x => x.HttpContext.User).Returns(principal.Object); var controller = new IndividualController( mockedIndividualService.Object, mockedMapper.Object, mockedPhotoHelper.Object, mockedUserProvider.Object); //controller.ControllerContext = controllerContext.Object; // Act controller.EventsList(username); // Assert mockedMapper.Verify(x => x.Map <EventViewModel>( It.IsAny <SofiaDayAndNight.Data.Models.Event>()), Times.Exactly(3)); }
public void ClientConnect([Values(false, true)] bool registerConnectCallback, [Values(false, true)] bool returnClientSocket) { // Setup AsyncCallback clientConnect = null; Mock <ISocket> mockSocket = new Mock <ISocket>(); Mock <ISocket> mockClientSocket = new Mock <ISocket>(); Mock <IAsyncResult> mockAsyncResult = new Mock <IAsyncResult>(); SocketServer socketServer = new SocketServer(); Mock <ClientConnectDelegate> connectCallback = new Mock <ClientConnectDelegate>(); socketServer.OnClientConnect += registerConnectCallback ? connectCallback.Object : null; mockSocket.Setup(s => s.BeginAccept(It.IsAny <AsyncCallback>(), null)).Callback <AsyncCallback, object>((c, o) => clientConnect = c); mockSocket.Setup(s => s.EndAccept(mockAsyncResult.Object)).Returns(returnClientSocket ? mockClientSocket.Object : null); // Act socketServer.Start(mockSocket.Object, 6128); clientConnect(mockAsyncResult.Object); // Verify mockSocket.Verify(s => s.Bind(It.IsAny <System.Net.EndPoint>()), Times.Once()); mockSocket.Verify(s => s.Listen(1), Times.Once()); mockSocket.Verify(s => s.BeginAccept(It.IsAny <AsyncCallback>(), null), Times.Exactly(2)); mockSocket.Verify(s => s.EndAccept(It.IsAny <IAsyncResult>())); mockClientSocket.Verify(s => s.BeginReceive(It.IsAny <byte[]>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <System.Net.Sockets.SocketFlags>(), It.IsAny <AsyncCallback>(), It.IsAny <object>()), Times.Exactly(returnClientSocket ? 1 : 0)); connectCallback.Verify(c => c(It.IsAny <SocketConnection>()), Times.Exactly((returnClientSocket && registerConnectCallback) ? 1 : 0)); // Note that calling VerifyNoOtherCalls on one Mock<ISocket> checks all Mock<ISocket> instances. // This is apparently a known issue with Moq. See https://github.com/moq/moq4/issues/892. mockSocket.VerifyNoOtherCalls(); }
public async Task ShouldContinueUntilResponseOk() { // Setting 3 ranges, first one returns a 304, second returns Ok MultiRangeMockDocumentClient documentClient = new MultiRangeMockDocumentClient(); using CosmosClient client = MockCosmosUtil.CreateMockCosmosClient(); Mock <CosmosClientContext> mockContext = new Mock <CosmosClientContext>(); mockContext.Setup(x => x.ClientOptions).Returns(MockCosmosUtil.GetDefaultConfiguration()); mockContext.Setup(x => x.DocumentClient).Returns(documentClient); mockContext.Setup(x => x.SerializerCore).Returns(MockCosmosUtil.Serializer); mockContext.Setup(x => x.Client).Returns(client); mockContext.Setup(x => x.CreateLink(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())).Returns("/dbs/test/colls/test"); ResponseMessage firstResponse = new ResponseMessage(HttpStatusCode.NotModified); firstResponse.Headers.ETag = "FirstContinuation"; ResponseMessage secondResponse = new ResponseMessage(HttpStatusCode.OK); secondResponse.Headers.ETag = "SecondContinuation"; mockContext.SetupSequence(x => x.ProcessResourceOperationAsync <ResponseMessage>( It.IsAny <string>(), It.IsAny <Documents.ResourceType>(), It.IsAny <Documents.OperationType>(), It.IsAny <RequestOptions>(), It.IsAny <ContainerInternal>(), It.IsAny <PartitionKey?>(), It.IsAny <Stream>(), It.IsAny <Action <RequestMessage> >(), It.IsAny <Func <ResponseMessage, ResponseMessage> >(), It.IsAny <CosmosDiagnosticsContext>(), It.IsAny <CancellationToken>())) .Returns(Task.FromResult(firstResponse)) .Returns(Task.FromResult(secondResponse)); DatabaseInternal databaseCore = new DatabaseInlineCore(mockContext.Object, "mydb"); StandByFeedIteratorCore iterator = new StandByFeedIteratorCore( mockContext.Object, new ContainerInlineCore(mockContext.Object, databaseCore, "myColl"), ChangeFeedStartFrom.Beginning(), new ChangeFeedRequestOptions() { PageSizeHint = 10, }); ResponseMessage firstRequest = await iterator.ReadNextAsync(); Assert.IsTrue(firstRequest.Headers.ContinuationToken.Contains(firstResponse.Headers.ETag), "Response should contain the first continuation"); Assert.IsTrue(firstRequest.Headers.ContinuationToken.Contains(secondResponse.Headers.ETag), "Response should contain the second continuation"); Assert.AreEqual(HttpStatusCode.OK, firstRequest.StatusCode); mockContext.Verify(x => x.ProcessResourceOperationAsync <ResponseMessage>( It.IsAny <string>(), It.IsAny <Documents.ResourceType>(), It.IsAny <Documents.OperationType>(), It.IsAny <RequestOptions>(), It.IsAny <ContainerInternal>(), It.IsAny <PartitionKey?>(), It.IsAny <Stream>(), It.IsAny <Action <RequestMessage> >(), It.IsAny <Func <ResponseMessage, ResponseMessage> >(), It.IsAny <CosmosDiagnosticsContext>(), It.IsAny <CancellationToken>()), Times.Exactly(2)); }
public async Task Test_ProcessImages_Should_Call_ISaveFileService_The_Number_Of_Times_The_Loop_Runs() { var result = await _imageRepository.ProcessImages(5); _mockSaveFileService.Verify(service => service.Save(It.IsAny <ImageFile>()), Times.Exactly(5)); _mockProcessImageService.Verify(service => service.GenerateFile(It.IsAny <string>()), Times.Exactly(5)); }
public void VerifyListCalled(int timesCalled) { _mockIBlogPostDataAccessAdapter .Verify(x => x.List(), Times.Exactly(timesCalled)); }
public void GenerateIntegerList(int times) { var mockSuit = new Mock <Suit>(); var primitiveGenerator = new PrimitiveGenerator(mockSuit.Object); mockSuit.Setup(i => i.GeneratePrimitive <int>("test", It.IsAny <ISessionManager>())) .Returns(10); var result = primitiveGenerator.Integer("test", count: times); Assert.All(result, i => Assert.Equal(10, i)); mockSuit.Verify(i => i.GeneratePrimitive <int>("test", It.IsAny <ISessionManager>()), Times.Exactly(times)); }
public void VerifyDeleteCalled(int timesCalled) { _mockIBlogPostDataAccessAdapter .Verify(x => x.Delete(It.IsAny <BlogPost>()), Times.Exactly(timesCalled)); }
public void CursorEditor_EditValue_ValidProvider_ReturnsValue(object value) { var editor = new CursorEditor(); var mockEditorService = new Mock <IWindowsFormsEditorService>(MockBehavior.Strict); var mockServiceProvider = new Mock <IServiceProvider>(MockBehavior.Strict); mockServiceProvider .Setup(p => p.GetService(typeof(IWindowsFormsEditorService))) .Returns(mockEditorService.Object) .Verifiable(); mockEditorService .Setup(e => e.DropDownControl(It.IsAny <Control>())) .Verifiable(); Assert.Equal(value, editor.EditValue(null, mockServiceProvider.Object, value)); mockServiceProvider.Verify(p => p.GetService(typeof(IWindowsFormsEditorService)), Times.Once()); mockEditorService.Verify(e => e.DropDownControl(It.IsAny <Control>()), Times.Once()); // Edit again. Assert.Equal(value, editor.EditValue(null, mockServiceProvider.Object, value)); mockServiceProvider.Verify(p => p.GetService(typeof(IWindowsFormsEditorService)), Times.Exactly(2)); mockServiceProvider.Verify(p => p.GetService(typeof(IWindowsFormsEditorService)), Times.Exactly(2)); }