public void BytesDistributedWithAdditionShouldBeCorrect() { IHttp2Stream streamE = connection.Local.CreateStream(STREAM_E, false); this.SetPriority(streamE.Id, STREAM_A, Http2CodecUtil.DefaultPriorityWeight, true); // Send a bunch of data on each stream. this.InitState(STREAM_A, 400, true); this.InitState(STREAM_B, 500, true); this.InitState(STREAM_C, 600, true); this.InitState(STREAM_D, 700, true); this.InitState(STREAM_E, 900, true); Assert.True(this.Write(900)); Assert.Equal(400, this.CaptureWrites(STREAM_A)); Assert.Equal(500, this.CaptureWrites(STREAM_B)); this.VerifyNeverWrite(STREAM_C); this.VerifyNeverWrite(STREAM_D); this.VerifyWrite(Times.AtMost(1), STREAM_E, 0); Assert.True(this.Write(900)); Assert.Equal(400, this.CaptureWrites(STREAM_A)); Assert.Equal(500, this.CaptureWrites(STREAM_B)); this.VerifyWrite(Times.AtMost(1), STREAM_C, 0); this.VerifyWrite(Times.AtMost(1), STREAM_D, 0); Assert.Equal(900, this.CaptureWrites(STREAM_E)); Assert.False(this.Write(1301)); Assert.Equal(400, this.CaptureWrites(STREAM_A)); Assert.Equal(500, this.CaptureWrites(STREAM_B)); Assert.Equal(600, this.CaptureWrites(STREAM_C)); Assert.Equal(700, this.CaptureWrites(STREAM_D)); Assert.Equal(900, this.CaptureWrites(STREAM_E)); }
protected override void CheckMockInvocations(int nrOfPassedTests, int nrOfFailedTests, int nrOfUnexecutedTests, int nrOfSkippedTests) { base.CheckMockInvocations(nrOfPassedTests, nrOfFailedTests, nrOfUnexecutedTests, nrOfSkippedTests); if (nrOfPassedTests > 0) { MockFrameworkHandle.Verify(h => h.RecordResult(It.Is <TestResult>(tr => tr.Outcome == TestOutcome.Passed)), Times.AtLeast(nrOfPassedTests)); MockFrameworkHandle.Verify(h => h.RecordEnd(It.IsAny <TestCase>(), It.Is <TestOutcome>(to => to == TestOutcome.Passed)), Times.AtLeast(nrOfPassedTests)); } if (nrOfFailedTests > 0) { MockFrameworkHandle.Verify(h => h.RecordResult(It.Is <TestResult>(tr => tr.Outcome == TestOutcome.Failed)), Times.AtLeast(nrOfFailedTests)); MockFrameworkHandle.Verify(h => h.RecordEnd(It.IsAny <TestCase>(), It.Is <TestOutcome>(to => to == TestOutcome.Failed)), Times.AtLeast(nrOfFailedTests)); } MockFrameworkHandle.Verify(h => h.RecordResult(It.Is <TestResult>(tr => tr.Outcome == TestOutcome.Skipped)), Times.AtMost(nrOfSkippedTests)); MockFrameworkHandle.Verify(h => h.RecordEnd(It.IsAny <TestCase>(), It.Is <TestOutcome>(to => to == TestOutcome.Skipped)), Times.AtMost(nrOfSkippedTests)); }
public void Call_NotMoreThen3CallsPerSecond() { Json = @"{ ""response"": 2 }"; Api.RequestsPerSecond = 3; // Переопределение значения в базовом классе var invocationCount = 0; Mock.Get(Api.Browser) .Setup(m => m.GetJson(It.IsAny <string>(), It.IsAny <IEnumerable <KeyValuePair <string, string> > >())) .Returns(Json) .Callback(delegate { invocationCount++; }); var start = DateTimeOffset.Now; while (true) { Api.Call("someMethod", VkParameters.Empty, true); var total = (int)(DateTimeOffset.Now - start).TotalMilliseconds; if (total > 999) { break; } } // Не больше 4 раз, т.к. 4-ый раз вызывается через 1002 мс после первого вызова, а total выходит через 1040 мс // переписать тест, когда придумаю более подходящий метод проверки Mock.Get(Api.Browser) .Verify(m => m.GetJson( It.IsAny <string>(), It.IsAny <IEnumerable <KeyValuePair <string, string> > >() ), Times.AtMost(4) ); }
public virtual void Log_only_after_a_threshold_is_reached() { var problems = LogEvents().SkipUntil( LogEvents().Where(e => e.Subject is Exception)); var observer = new Mock <IObserver <LogEntry> >(); observer.Setup(o => o.OnNext(It.IsAny <LogEntry>())); using (problems.Subscribe(e => Console.WriteLine(e.Message))) using (problems.Subscribe(observer.Object)) { var thread = new Thread( () => { for (var i = 0; i <= 5000; i++) { // this won't appear in the log until the exceptions start happening: Log.Write("Message " + i); if (i > 4995) { Log.Write(() => new InvalidOperationException()); } } }); thread.Start(); Thread.Sleep(5000); thread.Abort(); } observer.Verify( o => o.OnNext(It.IsAny <LogEntry>()), Times.AtMost(8)); }
public void BytesDistributedWithRestructureShouldBeCorrect() { this.InitState(STREAM_A, 400, true); this.InitState(STREAM_B, 500, true); this.InitState(STREAM_C, 600, true); this.InitState(STREAM_D, 700, true); this.SetPriority(STREAM_B, STREAM_A, Http2CodecUtil.DefaultPriorityWeight, true); Assert.True(this.Write(500)); Assert.Equal(400, this.CaptureWrites(STREAM_A)); this.VerifyWrite(STREAM_B, 100); this.VerifyNeverWrite(STREAM_C); this.VerifyNeverWrite(STREAM_D); Assert.True(this.Write(400)); Assert.Equal(400, this.CaptureWrites(STREAM_A)); Assert.Equal(500, this.CaptureWrites(STREAM_B)); this.VerifyWrite(Times.AtMost(1), STREAM_C, 0); this.VerifyWrite(Times.AtMost(1), STREAM_D, 0); Assert.False(this.Write(1300)); Assert.Equal(400, this.CaptureWrites(STREAM_A)); Assert.Equal(500, this.CaptureWrites(STREAM_B)); Assert.Equal(600, this.CaptureWrites(STREAM_C)); Assert.Equal(700, this.CaptureWrites(STREAM_D)); }
public void Should_do_not_update_auctions_fineshed() { //Given DateTime data = new DateTime(2016, 2, 15); Leilao leilao1 = new Leilao("Tv 20 polegadas"); leilao1.naData(data); List <Leilao> listaRetorno = new List <Leilao>(); listaRetorno.Add(leilao1); var dao = new Mock <LeilaoDaoFalso>(); var carteiro = new Mock <Carteiro>(); dao.Setup(m => m.Correntes()).Returns(listaRetorno); //When EncerradorDeLeilao encerrador = new EncerradorDeLeilao(dao.Object, carteiro.Object); encerrador.Encerra(); // verify aqui ! dao.Verify(d => d.Salva(leilao1), Times.Never()); dao.Verify(d => d.Atualiza(leilao1), Times.Exactly(1)); dao.Verify(d => d.Atualiza(leilao1), Times.AtLeastOnce()); dao.Verify(d => d.Correntes(), Times.AtLeastOnce()); dao.Verify(d => d.Correntes(), Times.AtLeast(1)); dao.Verify(d => d.Atualiza(leilao1), Times.AtMost(1)); dao.Verify(d => d.Correntes(), Times.AtMost(1)); //Then }
public void Mute_CallsQuieterNoMoreThanTenTimes_WhenCurrentVolumeNeverReturnsZero() { var mock = new Mock <IVolume>(); var volume = 120; mock.Setup(m => m.CurrentVolume()).Returns(() => volume.ToString()); mock.Setup(m => m.Quieter(It.IsAny <int>())).Returns <int>(v => { volume -= v; return(volume); }); var mockObject = mock.Object; Mute(mockObject); var wasAnExceptionThrown = false; try { mock.Verify(x => x.Quieter(It.IsAny <int>()), Times.AtMost(10)); } catch (Exception) { wasAnExceptionThrown = true; } Assert.AreEqual(false, wasAnExceptionThrown); }
public void SaveButtonClickFalseValidationTest(bool validName, bool validStatus, bool expFlag) { _modelCreatorMock.Setup(f => f.GetRequestModel(It.IsAny <IEditProfileEntity>())) .Returns(It.IsAny <UserInfoDTO>()); _controllerMock.Setup(f => f.Send(It.IsAny <UserInfoDTO>())); var entity = new Mock <IEditProfileEntity>(); entity.SetupGet(f => f.FirstName).Returns("FirstName"); entity.SetupGet(f => f.LastName).Returns("LastName"); entity.SetupGet(f => f.UserStatus).Returns("UserStatus"); _validationMock.Setup(f => f.CheckName(It.IsAny <string>())).Returns(validName); _validationMock.Setup(f => f.CheckStatus(It.IsAny <string>())).Returns(validStatus); var flag = !expFlag; _interactor.ValidationFieldResponse += (fields, b) => { flag = b; }; _interactor.SaveButtonClick(entity.Object); Assert.AreEqual(expFlag, flag); _modelCreatorMock.Verify(f => f.GetRequestModel(It.IsAny <IEditProfileEntity>()), Times.Never); _controllerMock.Verify(f => f.Send(It.IsAny <UserInfoDTO>()), Times.Never); _validationMock.Verify(f => f.CheckName(It.IsAny <string>()), Times.AtMost(2)); _validationMock.Verify(f => f.CheckStatus(It.IsAny <string>()), Times.AtMostOnce); }
public async Task ItemSale_CalculateProperties_Success() { // Arrange var mocker = new AutoMocker(); var itemSales = new List <ItemSale> { new ItemSale(0, 0, 1, 2, 0, 0) }; var percentage = new Faker().Random.Decimal(1, 50); var vinylDisc = new Faker <VinylDisc>() .CustomInstantiator(f => new VinylDisc(f.Random.Int(1, 20), f.Random.Int(1, 20), f.Lorem.Letter(20), f.Random.Decimal(1M, 100M))) .Generate(); mocker.GetMock <IVinylDiscDapperRepository>().Setup(v => v.GetById(It.IsAny <int>())) .Returns(Task.FromResult(vinylDisc)); mocker.GetMock <IConfigCashbackService>().Setup(c => c.GetPercentage(It.IsAny <int>())) .Returns(Task.FromResult(percentage)); var itemSaleService = mocker.CreateInstance <ItemSaleService>(); // Act await itemSaleService.CalculateProperties(itemSales); // Assert Assert.True(itemSales.All(i => i.Value > 0)); Assert.True(itemSales.All(i => i.Cashback > 0)); mocker.GetMock <IVinylDiscDapperRepository>() .Verify(v => v.GetById(It.IsAny <int>()), Times.AtMost(itemSales.Count)); mocker.GetMock <IConfigCashbackService>() .Verify(c => c.GetPercentage(It.IsAny <int>()), Times.AtMost(itemSales.Count)); }
public async Task CheckStaleIntervalTests() { var activityId = Guid.NewGuid().ToString(); var workerInfo = new MockWorkerInfo(); var settings = new ScaleSettings { StaleWorkerCheckInterval = TimeSpan.FromMilliseconds(500) }; using (var scaleManager = new MockScaleManager(MockBehavior.Strict, settings)) { // Setup scaleManager.MockWorkerTable.Setup(t => t.List()) .Returns(Task.FromResult(Enumerable.Empty <IWorkerInfo>())); scaleManager.MockScaleTracer.Setup(t => t.TraceInformation(activityId, workerInfo, It.IsAny <string>())); // Test for (int i = 0; i < 10; ++i) { await scaleManager.MockCheckStaleWorker(activityId, workerInfo); await Task.Delay(100); } // Assert scaleManager.MockWorkerTable.Verify(t => t.List(), Times.AtLeast(1)); scaleManager.MockWorkerTable.Verify(t => t.List(), Times.AtMost(4)); } }
private void BlockedStreamShouldSpreadDataToChildren(bool streamAShouldWriteZero) { this.InitState(STREAM_B, 10, true); this.InitState(STREAM_C, 10, true); this.InitState(STREAM_D, 10, true); // Write up to 10 bytes. Assert.True(this.Write(10)); if (streamAShouldWriteZero) { this.VerifyWrite(STREAM_A, 0); } else { this.VerifyNeverWrite(STREAM_A); } this.VerifyWrite(Times.AtMost(1), STREAM_C, 0); this.VerifyWrite(Times.AtMost(1), STREAM_D, 0); // B is entirely written this.VerifyWrite(STREAM_B, 10); // Now test that writes get delegated from A (which is blocked) to its children Assert.True(this.Write(5)); if (streamAShouldWriteZero) { this.VerifyWrite(Times.Exactly(1), STREAM_A, 0); } else { this.VerifyNeverWrite(STREAM_A); } this.VerifyWrite(STREAM_D, 5); this.VerifyWrite(Times.AtMost(1), STREAM_C, 0); Assert.True(this.Write(5)); if (streamAShouldWriteZero) { this.VerifyWrite(Times.Exactly(1), STREAM_A, 0); } else { this.VerifyNeverWrite(STREAM_A); } Assert.Equal(10, this.CaptureWrites(STREAM_C) + this.CaptureWrites(STREAM_D)); Assert.True(this.Write(5)); Assert.False(this.Write(5)); if (streamAShouldWriteZero) { this.VerifyWrite(Times.Exactly(1), STREAM_A, 0); } else { this.VerifyNeverWrite(STREAM_A); } this.VerifyWrite(Times.Exactly(2), STREAM_C, 5); this.VerifyWrite(Times.Exactly(2), STREAM_D, 5); }
public void Call_NotMoreThen3CallsPerSecond() { Json = @"{ ""response"": 2 }"; Api.RequestsPerSecond = 3; // Переопределение значения в базовом классе Mock.Get(Api.RestClient) .Setup(m => m.PostAsync(It.IsAny <Uri>(), It.IsAny <IEnumerable <KeyValuePair <string, string> > >())) .Returns(Task.FromResult(HttpResponse <string> .Success(HttpStatusCode.OK, Json, Url))); var start = DateTimeOffset.Now; while (true) { Api.Call("someMethod", VkParameters.Empty, true); var total = (int)(DateTimeOffset.Now - start).TotalMilliseconds; if (total > 999) { break; } } // Не больше 4 раз, т.к. 4-ый раз вызывается через 1002 мс после первого вызова, а total выходит через 1040 мс // переписать тест, когда придумаю более подходящий метод проверки Mock.Get(Api.RestClient) .Verify(m => m.PostAsync(It.IsAny <Uri>(), It.IsAny <IEnumerable <KeyValuePair <string, string> > >()), Times.AtMost(4)); }
public void MinChunkShouldBeAllocatedPerStream() { // Re-assign weights. this.SetPriority(STREAM_A, 0, (short)50, false); this.SetPriority(STREAM_B, 0, (short)200, false); this.SetPriority(STREAM_C, STREAM_A, (short)100, false); this.SetPriority(STREAM_D, STREAM_A, (short)100, false); // Update the streams. this.InitState(STREAM_A, ALLOCATION_QUANTUM, true); this.InitState(STREAM_B, ALLOCATION_QUANTUM, true); this.InitState(STREAM_C, ALLOCATION_QUANTUM, true); this.InitState(STREAM_D, ALLOCATION_QUANTUM, true); // Only write 3 * chunkSize, so that we'll only write to the first 3 streams. int written = 3 * ALLOCATION_QUANTUM; Assert.True(this.Write(written)); Assert.Equal(ALLOCATION_QUANTUM, this.CaptureWrites(STREAM_A)); Assert.Equal(ALLOCATION_QUANTUM, this.CaptureWrites(STREAM_B)); Assert.Equal(ALLOCATION_QUANTUM, this.CaptureWrites(STREAM_C)); this.VerifyWrite(Times.AtMost(1), STREAM_D, 0); // Now write again and verify that the last stream is written to. Assert.False(this.Write(ALLOCATION_QUANTUM)); Assert.Equal(ALLOCATION_QUANTUM, this.CaptureWrites(STREAM_A)); Assert.Equal(ALLOCATION_QUANTUM, this.CaptureWrites(STREAM_B)); Assert.Equal(ALLOCATION_QUANTUM, this.CaptureWrites(STREAM_C)); Assert.Equal(ALLOCATION_QUANTUM, this.CaptureWrites(STREAM_D)); }
public void Call_NotMoreThen3CallsPerSecond() { int invocationCount = 0; var browser = new Mock <IBrowser>(); browser.Setup(m => m.GetJson(It.IsAny <string>())) .Returns(@"{ ""response"": 2 }") .Callback(() => invocationCount++); var api = new VkApi { Browser = browser.Object }; var start = DateTimeOffset.Now; while (true) { api.Call("someMethod", VkParameters.Empty, true); int total = (int)(DateTimeOffset.Now - start).TotalMilliseconds; if (total > 999) { break; } } // Не больше 4 раз, т.к. 4-ый раз вызывается через 1002 мс после первого вызова, а total выходит через 1040 мс // переписать тест, когда придумаю более подходящий метод проверки browser.Verify(m => m.GetJson(It.IsAny <string>()), Times.AtMost(4)); }
public void TestForeflightSending() { FlightData data = DEFUALT_DATA; string GPS_STRING = "XGPSMSFS 2020,5.5000,4.4000,1.1,3.30,2.2"; string ATTITUDE_STRING = "XATTMSFS 2020,8.8,6.6,7.7"; var mock = new Mock <ForeFlightSender>(MockBehavior.Default, data, new UdpClient()) { CallBase = true }; ForeFlightSender sender = mock.Object; mock.Protected().SetupGet <FlightData>("FlightData").Returns(data); mock.Protected().Setup("Send", ItExpr.IsAny <string>()) .Callback((string msg) => { }); IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), ForeFlightSender.DEFAULT_PORT); sender.EndPoint = endpoint; sender.Start(); System.Threading.Thread.Sleep(5100); sender.Stop(); System.Threading.Thread.Sleep(1100); mock.Protected().Verify("Send", Times.Exactly(5), ItExpr.Is <string>(s => GPS_STRING.Equals(s))); // giving some leway on Attitude sending just in case of lag. mock.Protected().Verify("Send", Times.AtLeast(31), ItExpr.Is <string>(s => ATTITUDE_STRING.Equals(s))); mock.Protected().Verify("Send", Times.AtMost(32), ItExpr.Is <string>(s => ATTITUDE_STRING.Equals(s))); }
public async Task should_back_off_when_reached_max_failures() { var httpMessageHandlerMock = new Mock <HttpMessageHandler>(); httpMessageHandlerMock.Protected() .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .Returns(Task.FromResult(new HttpResponseMessage(HttpStatusCode.BadRequest))); var policy = new HttpPolicy { FailuresBeforeBackoff = 3 }; var client = new DefaultLineProtocolClient(new LoggerFactory(), new InfluxDBSettings("influx", new Uri("http://localhost")), policy, httpMessageHandlerMock.Object); foreach (var attempt in Enumerable.Range(0, 10)) { await client.WriteAsync(_payload, CancellationToken.None); // ReSharper disable ConvertIfStatementToConditionalTernaryExpression if (attempt <= policy.FailuresBeforeBackoff) // ReSharper restore ConvertIfStatementToConditionalTernaryExpression { httpMessageHandlerMock.Protected() .Verify <Task <HttpResponseMessage> >("SendAsync", Times.AtLeastOnce(), ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()); } else { httpMessageHandlerMock.Protected() .Verify <Task <HttpResponseMessage> >("SendAsync", Times.AtMost(3), ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()); } } }
public async Task Should_back_off_when_reached_max_failures_then_retry_after_backoff_period() { var httpMessageHandlerMock = new Mock <HttpMessageHandler>(); httpMessageHandlerMock.Protected().Setup <Task <HttpResponseMessage> >( "SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()). Returns(Task.FromResult(new HttpResponseMessage(HttpStatusCode.BadRequest))); var policy = new HttpPolicy { FailuresBeforeBackoff = 3, BackoffPeriod = TimeSpan.FromSeconds(1) }; var settings = new MetricsReportingHostedMetricsOptions { HostedMetrics = new HostedMetricsOptions { BaseUri = new Uri("http://localhost"), ApiKey = "123" }, HttpPolicy = new HttpPolicy() }; var hostedMetricsClient = HostedMetricsReporterBuilder.CreateClient(settings, policy, httpMessageHandlerMock.Object); foreach (var attempt in Enumerable.Range(0, 10)) { await hostedMetricsClient.WriteAsync(Payload, CancellationToken.None); if (attempt <= policy.FailuresBeforeBackoff) { httpMessageHandlerMock.Protected().Verify <Task <HttpResponseMessage> >( "SendAsync", Times.AtLeastOnce(), ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()); } else { httpMessageHandlerMock.Protected().Verify <Task <HttpResponseMessage> >( "SendAsync", Times.AtMost(3), ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()); } } await Task.Delay(policy.BackoffPeriod); httpMessageHandlerMock = new Mock <HttpMessageHandler>(); httpMessageHandlerMock.Protected().Setup <Task <HttpResponseMessage> >( "SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()).Returns(Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK))); hostedMetricsClient = HostedMetricsReporterBuilder.CreateClient(settings, policy, httpMessageHandlerMock.Object); var response = await hostedMetricsClient.WriteAsync(Payload, CancellationToken.None); response.Success.Should().BeTrue(); }
public void AtMost_n_deconstructs_to_0_n() { const int n = 42; var(from, to) = Times.AtMost(n); Assert.Equal(0, from); Assert.Equal(n, to); }
public async Task CanReceiveEndpointClientEvents() { var testSubscriptionPath = "events/subscriptions/specific-events-1"; _messageTypePathMappings.Add(new MessageTypeMessagingEntityMappingDetails(typeof(TestSpecificEvent1), testSubscriptionPath, MessagingEntityType.Subscription)); var publishedEventBrokeredMessageTaskCompletionSource = new TaskCompletionSource <BrokeredMessage>(); var mockMessageReceiver = new Mock <IMessageReceiver>(); mockMessageReceiver.Setup(mr => mr.ReceiveAsync()) .Returns(() => publishedEventBrokeredMessageTaskCompletionSource.Task); _mockMessagingFactory.Setup(mf => mf.CreateMessageReceiver(It.IsNotNull <Type>(), It.IsNotNull <string>(), It.IsAny <MessageReceiveMode>())) .Returns(mockMessageReceiver.Object); var mockMessageSender = new Mock <IMessageSender>(); mockMessageSender.Setup(mr => mr.SendAsync(It.IsNotNull <BrokeredMessage>())) .Callback <BrokeredMessage>(bm => { publishedEventBrokeredMessageTaskCompletionSource.SetResult(bm); publishedEventBrokeredMessageTaskCompletionSource = new TaskCompletionSource <BrokeredMessage>(); }) .Returns(Task.FromResult(true)); _mockMessagingFactory.Setup(mf => mf.CreateMessageSender(It.IsNotNull <Type>(), It.IsNotNull <string>())) .Returns(mockMessageSender.Object); var endpointProvider = new AzureServiceBusEndpointProvider <TestMessage, TestMessage, TestCommand, TestEvent, TestRequest, TestResponse>( "TestEndpoint", _mockMessagingFactory.Object, new JsonMessageSerializer(), new JsonMessageDeserializerFactory(typeof(JsonMessageDeserializer <>)), _messageTypePathMappings, _testAssemblyFilter, _testMessageTypeFilter, _messagePropertyProviderManager, _mockMessageOutgoingPropertiesTable.Object); var endpointClient = endpointProvider.CreateEndpointClient(); var publishedEvents = endpointClient.Events.Replay(); using (publishedEvents.Connect()) { await endpointProvider.CreateEndpoint().PublishAsync(new TestSpecificEvent1 { TestId = 1234 }); var testEvent = await publishedEvents.FirstOrDefaultAsync(); testEvent.Should().NotBeNull(); testEvent.TestId.Should().Be(1234); } _mockMessagingFactory.Verify(mf => mf.CreateMessageReceiver(It.Is <Type>(it => it == typeof(TestSpecificEvent1)), testSubscriptionPath, It.Is <MessageReceiveMode>(mrm => mrm == MessageReceiveMode.ReceiveAndDelete)), Times.Once()); /* NOTE: it's possible ReceiveAsync will be called up to two times due to concurrency here: * the first time will return the msg for the test, but then it's possible there will be a second call to ReceiveAsync to wait for the next message * before the subscription is shut down. */ mockMessageReceiver.Verify(mr => mr.ReceiveAsync(), Times.AtMost(2)); }
public void WithMock() { var searchViewModel = new VisualizerViewModel(); _presenter.Initialize(searchViewModel); _viewMock.VerifySet(v => v.ViewModel = searchViewModel, Times.Once()); _viewMock.VerifyGet(v => v.ViewModel, Times.AtMost(2)); }
public void Move_CallMove_CallSingleInvokerSameCount() { string command = "TESTCOMMAND"; var instance = new MultipleCommandInvoker(SingleCommandInvoker.Object); instance.Move(command, null); SingleCommandInvoker.Verify(x => x.Move(It.IsAny <string>(), null), Times.AtLeast(command.Length)); SingleCommandInvoker.Verify(x => x.Move(It.IsAny <string>(), null), Times.AtMost(command.Length)); }
public void TooMany_does_not_cause_timeout_wait() { var t = Times.AtMost(3); var stopwatch = Stopwatch.StartNew(); Assert.AreEqual(Times.Result.TooMany, t.Verify(4, TimeSpan.FromSeconds(1))); stopwatch.Stop(); Assert.LessOrEqual(stopwatch.ElapsedMilliseconds, 100); }
public void Register_Db_Connection_Factory_And_Find() { var dbConnectionName = new DbConnectionName("name"); var provider = new DbConnectionFactoryProvider(); var mockFactory = new Mock <IDbConnectionFactory>(); mockFactory.Verify(tt => tt.Create(null), Times.AtMost(1)); provider.Add(dbConnectionName, mockFactory.Object); provider.Create(dbConnectionName).Create(null); mockFactory.VerifyAll(); }
public void AtMostRangesBetweenZeroAndTimes() { var target = Times.AtMost(10); Assert.IsFalse(target.Verify(-1)); Assert.IsTrue(target.Verify(0)); Assert.IsTrue(target.Verify(6)); Assert.IsTrue(target.Verify(10)); Assert.IsFalse(target.Verify(11)); Assert.IsFalse(target.Verify(int.MaxValue)); }
public void AtMostRangesBetweenZeroAndTimes() { var target = Times.AtMost(10); Assert.False(target.Validate(-1)); Assert.True(target.Validate(0)); Assert.True(target.Validate(6)); Assert.True(target.Validate(10)); Assert.False(target.Validate(11)); Assert.False(target.Validate(int.MaxValue)); }
public void ShouldCallChecker() { var checker = new Mock <IPrimeChecker>(); checker.Setup(x => x.IsPrime(It.IsAny <int>())); var runner = new SequencialRunner(checker.Object); var topLimit = 100; var result = runner.GetAllNumbers(topLimit); checker.Verify(x => x.IsPrime(It.IsAny <int>()), Times.AtMost(topLimit - 2)); }
public static async Task GetAsync_InvokesGetOrder( [Frozen] Mock <ISupplierSectionService> service, [Frozen] CallOffId callOffId, Order order, SupplierSectionController controller) { order.Supplier.Should().NotBeNull(); service.Setup(o => o.GetOrder(callOffId)).ReturnsAsync(order); await controller.GetAsync(callOffId); service.Verify(o => o.GetOrder(callOffId), () => Times.AtMost(1)); }
public void VoiceAttackPluginTests_ShutdownFSUIPCInterfaceOnExit() { var mockInterface = new Mock <IFSUIPCInterface>(); MyVAProxy proxy = new MyVAProxy(); proxy.SessionState.Add(VoiceAttackPlugin.SESSIONSTATE.KEY_FSUIPCINTERFACE, mockInterface.Object); // Call Exit1 VoiceAttackPlugin.VA_Exit1(proxy); mockInterface.Verify(x => x.shutdown(), Times.AtMost(1)); }
public void Exit_Command_Should_Call_Exit_On_NavigationService() { var mockMessageService = new Mock <IMessagingService>(); var mockNavigationService = new Mock <INavigationService>(); mockNavigationService.Verify(tt => tt.Exit(), Times.AtMost(1)); var viewModel = new MainViewModel(mockNavigationService.Object, mockMessageService.Object); viewModel.ExitCommand.Execute(null); mockNavigationService.Verify(); }
public async Task NaoDeveProcessarMensagemVazia() { var conexao = CriarConexao(); await _gerenciadorDeChat.Conectar(conexao.Apelido, conexao.Socket); SetupGerenciadorDeConexao(); await _gerenciadorDeChat.ProcessarMensagem(conexao.Socket, string.Empty); _gerenciadorDeSalaMock.Verify(_ => _.ObterSalaPorNome(It.IsAny <string>()), Times.AtMost(1)); }