public void Between_Inclusive() { Assert.Equal( "Between(123, 456, Inclusive)", Times.Between(123, 456, Range.Inclusive).ToString() ); }
public void ThrowsIfVerifyVoidBetweenExclusiveAndLessOrEqualsFromOrMoreOrEqualToCalls() { var mock = new Mock <IFoo>(); mock.Object.Submit(); var mex = Assert.Throws <MockException>( () => mock.Verify(foo => foo.Submit(), Times.Between(1, 4, Range.Exclusive))); Assert.Equal(MockException.ExceptionReason.VerificationFailed, mex.Reason); Assert.True(mex.Message.StartsWith( "\r\nExpected invocation on the mock between 1 and 4 times (Exclusive), but was 1 times: foo => foo.Submit()")); mock.Object.Submit(); mock.Verify(foo => foo.Submit(), Times.Between(1, 4, Range.Exclusive)); mock.Object.Submit(); mock.Verify(foo => foo.Submit(), Times.Between(1, 4, Range.Exclusive)); mock.Object.Submit(); mex = Assert.Throws <MockException>( () => mock.Verify(foo => foo.Submit(), Times.Between(1, 4, Range.Exclusive))); Assert.Equal(MockException.ExceptionReason.VerificationFailed, mex.Reason); Assert.True(mex.Message.StartsWith( "\r\nExpected invocation on the mock between 1 and 4 times (Exclusive), but was 4 times: foo => foo.Submit()")); }
public void Start_RunsForThreeIntervals_GetControlDefinitionIsCalledThreeTimes() { // Arrange var runDurationInMilliseconds = AgentCoordinationService.AgentControlDefinitionCheckIntervalInMilliseconds * 3; var agentControlDefinitionProvider = new Mock <IAgentControlDefinitionProvider>(); var agentControlDefinition = new AgentControlDefinition { AgentIsEnabled = true, Hostaddress = "127.0.0.1", Hostname = "www.example.com", CheckIntervalInSeconds = AgentCoordinationService.AgentControlDefinitionCheckIntervalInMilliseconds, SystemInformationSenderPath = "/api/systeminformation" }; agentControlDefinitionProvider.Setup(a => a.GetControlDefinition()).Returns(agentControlDefinition); var agentCoordinationService = new AgentCoordinationService(agentControlDefinitionProvider.Object, () => { }, () => { }); // Act var agentCoordinationServiceTask = new Task(agentCoordinationService.Start); agentCoordinationServiceTask.Start(); Task.WaitAll(new[] { agentCoordinationServiceTask }, runDurationInMilliseconds); // Assert agentControlDefinitionProvider.Verify(a => a.GetControlDefinition(), Times.Between(3, 4, Range.Inclusive)); }
public void BetweenExclusiveThrowsIfFromLessThanZero() { Assert.Throws <ArgumentOutOfRangeException>( () => Times.Between(-1, 10, Range.Exclusive) ); Assert.Throws <ArgumentOutOfRangeException>(() => Times.Between(-2, 3, Range.Exclusive)); }
public async Task Run_Job_With_Options_And_Raise_Exception() { // arrange var mockLogger = new Mock <ILogger <TestJobException> >(); var host = CreateHost(services => { // used for tests services.AddTransient <ILogger <TestJobException> >(x => mockLogger.Object); // short registration without UnobservedTaskExceptionHandler services.AddSchedulerJob <TestJobException, TestJobExceptionOptions>(); }); var client = new TestServer(host).CreateClient(); // act var response = await client.GetAsync("/hc"); response.EnsureSuccessStatusCode(); await Task.Delay(TimeSpan.FromSeconds(5)); // assert Assert.Equal("healthy", await response.Content.ReadAsStringAsync()); mockLogger.Verify( l => l.Log( LogLevel.Error, It.IsAny <EventId>(), It.Is <It.IsAnyType>(v => v.ToString().Contains(nameof(Exception))), It.IsAny <Exception>(), It.IsAny <Func <object, Exception, string> >()), Times.Between(1, 2, Range.Inclusive)); }
public void ThrowsIfVerifyGetGetBetweenInclusiveAndLessFromOrMoreToCalls() { var mock = new Mock <IFoo>(); var value = mock.Object.Value; MockException mex = Assert.Throws <MockException>( () => mock.VerifyGet(foo => foo.Value, Times.Between(2, 4, Range.Inclusive))); Assert.Equal(MockException.ExceptionReason.VerificationFailed, mex.Reason); value = mock.Object.Value; mock.VerifyGet(foo => foo.Value, Times.Between(2, 4, Range.Inclusive)); value = mock.Object.Value; mock.VerifyGet(foo => foo.Value, Times.Between(2, 4, Range.Inclusive)); value = mock.Object.Value; value = mock.Object.Value; mex = Assert.Throws <MockException>(() => mock.VerifyGet(foo => foo.Value, Times.Between(2, 4, Range.Inclusive))); Assert.Equal(MockException.ExceptionReason.VerificationFailed, mex.Reason); }
public void ThrowsIfVerifyReturningBetweenInclusiveAndLessFromOrMoreToCalls() { var mock = new Mock <IFoo>(); mock.Object.Execute(""); MockException mex = Assert.Throws <MockException>(() => mock.Verify(foo => foo.Execute(""), Times.Between(2, 4, Range.Inclusive))); Assert.Equal(MockException.ExceptionReason.VerificationFailed, mex.Reason); mock.Object.Execute(""); mock.Verify(foo => foo.Execute(""), Times.Between(2, 4, Range.Inclusive)); mock.Object.Execute(""); mock.Verify(foo => foo.Execute(""), Times.Between(2, 4, Range.Inclusive)); mock.Object.Execute(""); mock.Object.Execute(""); mex = Assert.Throws <MockException>( () => mock.Verify(foo => foo.Execute(""), Times.Between(2, 4, Range.Inclusive))); Assert.Equal(MockException.ExceptionReason.VerificationFailed, mex.Reason); }
public void ThrowsIfVerifyVoidBetweenInclusiveAndLessFromOrMoreToCalls() { var mock = new Mock <IFoo>(); mock.Object.Submit(); var mex = Assert.Throws <MockException>( () => mock.Verify(foo => foo.Submit(), Times.Between(2, 4, Range.Inclusive))); Assert.Equal(MockException.ExceptionReason.VerificationFailed, mex.Reason); Assert.True(mex.Message.Contains( "Expected invocation on the mock between 2 and 4 times (Inclusive), but was 1 times: foo => foo.Submit()")); mock.Object.Submit(); mock.Verify(foo => foo.Submit(), Times.Between(2, 4, Range.Inclusive)); mock.Object.Submit(); mock.Verify(foo => foo.Submit(), Times.Between(2, 4, Range.Inclusive)); mock.Object.Submit(); mock.Object.Submit(); mex = Assert.Throws <MockException>( () => mock.Verify(foo => foo.Submit(), Times.Between(2, 4, Range.Inclusive))); Assert.Equal(MockException.ExceptionReason.VerificationFailed, mex.Reason); Assert.True(mex.Message.Contains( "Expected invocation on the mock between 2 and 4 times (Inclusive), but was 5 times: foo => foo.Submit()")); }
public void Between_1_2_inclusive_equals_Between_0_3_exclusive() { Assert.Equal( Times.Between(2, 3, Range.Inclusive), Times.Between(1, 4, Range.Exclusive) ); }
public void BetweenInclusiveThrowsIfFromGreaterThanTo() { Assert.Throws <ArgumentOutOfRangeException>(() => Times.Between(3, 2, Range.Inclusive)); Assert.Throws <ArgumentOutOfRangeException>( () => Times.Between(-3, -2, Range.Inclusive) ); Assert.Throws <ArgumentOutOfRangeException>(() => Times.Between(0, -2, Range.Inclusive)); }
public void Test_CountRecursiveForBetweenValues() { int min = 10; int max = 21; int number = new Random().Next(min, max); avengerController.GetRecursiveMethod(number); mockRepo.Verify(x => x.GetRecursivelySomething(), Times.Between(min, max, Range.Inclusive)); }
public void BetweenInclusive_n_m_deconstructs_to_n_m() { const int n = 13; const int m = 42; var(from, to) = Times.Between(n, m, Range.Inclusive); Assert.Equal(n, from); Assert.Equal(m, to); }
public void BetweenExclusive_n_m_deconstructs_to__n_plus_1__m_minus_1() { const int n = 13; const int m = 42; var(from, to) = Times.Between(n, m, Range.Exclusive); Assert.Equal(n + 1, from); Assert.Equal(m - 1, to); }
internal static void ToString_Terse() { Tools.Asserter.Is("0", Times.Never.ToString()); Tools.Asserter.Is("1", Times.Once.ToString()); Tools.Asserter.Is("2", Times.Exactly(2).ToString()); Tools.Asserter.Is("[0-1]", Times.Max(1).ToString()); Tools.Asserter.Is("[1-*]", Times.Min(1).ToString()); Tools.Asserter.Is("[1-2]", Times.Between(1, 2).ToString()); }
public void Between_x_y_inclusive_does_not_equal_Between_x_y_exclusive() { const int x = 1; const int y = 10; Assert.NotEqual( Times.Between(x, y, Range.Inclusive), Times.Between(x, y, Range.Exclusive) ); }
public void CreateMethod_Save_WasCalled_ThreeTimes() { var mock = new Mock <ICustomerRepository>(); var cService = new CustomerService(mock.Object); //act cService.Create(_customerList); //assert mock.Verify(x => x.Save(It.IsAny <Customer>()), Times.Between(2, 5, Range.Inclusive)); }
public async Task HandleAsync_ShouldReturnTrueAndNotLog_WhenNoErrors() { // Arrange var blobUri = new Uri(_expectedInboxUrl); JObject operationContext = JObject.Parse("{}"); var topicEndpointUri = new Uri("https://www.topichost.com"); var testEvent = new EventGridEvent { EventTime = DateTime.UtcNow, EventType = CustomEventTypes.RequestBlobCopy, DataVersion = "1.0", Data = JsonConvert.SerializeObject(new RequestBlobMetadataCreateDTO { BlobUri = blobUri, OperationContext = JObject.FromObject(operationContext) }) }; var blobBaseClient = new BlobBaseClient(blobUri); var blobProperties = new BlobProperties(); // Arrange Mocks Mock.Get(_settingsProvider) .Setup(x => x.GetAppSettingsValue(Publishing.TopicOutboundEndpointSettingName)) .Returns(topicEndpointUri.ToString()); Mock.Get(_storageService) .Setup(x => x.GetBlobMetadataAsync(blobUri, It.IsAny <StorageClientProviderContext>())) .ReturnsAsync(new JObject() { }); Mock.Get(_eventGridPublisher) .Setup(x => x.PublishEventToTopic(It.IsAny <EventGridEvent>())) .ReturnsAsync(true); // Act var handleAsyncResult = await _handler.HandleAsync(testEvent).ConfigureAwait(true); // Assert handleAsyncResult.ShouldBe(true, "handleAsync should always return true"); Mock.Get(_logger).Verify(x => x.LogExceptionObject(It.IsAny <EventId>(), It.IsAny <Exception>(), It.IsAny <object>()), Times.Never, "No exceptions should be logged when all succeeds"); Mock.Get(_logger).Verify(x => x.LogEventObject(It.Is <EventId>(e => e.Id >= LogEventIds.FailedToDeserializeEventData.Id), It.IsAny <object>()), Times.Never, "No events with IDs greater than an error ID (could be any LogEventId here) should be logged"); Mock.Get(_storageService).Verify(x => x.GetBlobMetadataAsync(It.IsAny <Uri>(), It.IsAny <StorageClientProviderContext>()), Times.Once, "Should attempt to get blob metadata."); Mock.Get(_eventGridPublisher).Verify(x => x.PublishEventToTopic(It.IsAny <EventGridEvent>()), Times.Between(2, 2, Moq.Range.Inclusive), "Should only publish acknowledgement and output events"); }
public void BetweenExclusiveRangesBetweenFromPlusOneAndToMinusOne() { var target = Times.Between(10, 20, Range.Exclusive); Assert.False(target.Validate(0)); Assert.False(target.Validate(10)); Assert.True(target.Validate(11)); Assert.True(target.Validate(14)); Assert.True(target.Validate(19)); Assert.False(target.Validate(20)); Assert.False(target.Validate(int.MaxValue)); }
public void BetweenInclusiveRangesBetweenFromAndTo() { var target = Times.Between(10, 20, Range.Inclusive); Assert.IsFalse(target.Verify(0)); Assert.IsFalse(target.Verify(9)); Assert.IsTrue(target.Verify(10)); Assert.IsTrue(target.Verify(14)); Assert.IsTrue(target.Verify(20)); Assert.IsFalse(target.Verify(21)); Assert.IsFalse(target.Verify(int.MaxValue)); }
public void BetweenInclusiveRangesBetweenFromAndTo() { var target = Times.Between(10, 20, Range.Inclusive); Assert.False(target.Validate(0)); Assert.False(target.Validate(9)); Assert.True(target.Validate(10)); Assert.True(target.Validate(14)); Assert.True(target.Validate(20)); Assert.False(target.Validate(21)); Assert.False(target.Validate(int.MaxValue)); }
public async Task RunImmediately_Successfully() { // assign var mockLoggerTestJob = new Mock <ILogger <TestJob> >(); var mockLoggerTestJobException = new Mock <ILogger <TestJobException> >(); var host = CreateHost(services => { services.AddScheduler(ctx => { ctx.AddJob <TestJob>(_ => { return(new TestJob(mockLoggerTestJob.Object) { RunImmediately = true, CronSchedule = "*/10 * * * * *" }); }); services.AddTransient <ILogger <TestJobException> >(x => mockLoggerTestJobException.Object); ctx.AddJob <TestJobException, TestJobExceptionOptions>(); }); }); var client = new TestServer(host).CreateClient(); // act var response = await client.GetAsync("/hc"); response.EnsureSuccessStatusCode(); await Task.Delay(TimeSpan.FromSeconds(6)); // assert Assert.Equal("healthy", await response.Content.ReadAsStringAsync()); mockLoggerTestJob.Verify( l => l.Log( LogLevel.Information, It.IsAny <EventId>(), It.Is <It.IsAnyType>(v => v.ToString().Contains(nameof(TestJob))), It.IsAny <Exception>(), It.IsAny <Func <object, Exception, string> >()), Times.Between(1, 2, Range.Inclusive)); mockLoggerTestJobException.Verify( l => l.Log( LogLevel.Error, It.IsAny <EventId>(), It.Is <It.IsAnyType>(v => v.ToString().Contains(nameof(Exception))), It.IsAny <Exception>(), It.IsAny <Func <object, Exception, string> >()), Times.Between(1, 2, Range.Inclusive)); }
public void TestOpslaan_Succes_RedirectsToIndex() { _analyseRepo.Setup(a => a.GetById(1)).Returns(_analyse); var result = _controller.Opslaan(_analyse) as RedirectToActionResult; Assert.Equal("Index", result?.ActionName); Assert.Equal("Kairos", result?.ControllerName); // mag ook 2 zijn, want de thread kan misschien nog niet klaar zijn _analyseRepo.Verify(a => a.Save(), Times.Between(1, 2, Range.Inclusive)); }
public async Task ShouldDisplayJoke2Or3TimesIn25Seconds() { _ctxS = new CancellationTokenSource(); //_ctxS.CancelAfter(25000); var task = _randomJokeServiceMock.Object.StartAsync(_ctxS.Token); task.Wait(new TimeSpan(0, 0, 0, seconds: 25)); _randomJokeServiceMock.Verify(x => x.GetRandomJoke(), Times.Between(2, 3, Range.Inclusive)); _randomJokeServiceMock.Verify(x => x.DisplayRandomJoke(It.IsAny <string>()), Times.Between(2, 3, Range.Inclusive)); }
public async Task Job_RunDelayed_And_Raise_UnobservedTaskException() { // arrange var mockLogger = new Mock <ILogger <TestJobException> >(); var host = CreateHost(services => { services.AddScheduler(ctx => { var jobName = nameof(TestJobException); ctx.UnobservedTaskExceptionHandler = UnobservedTaskExceptionHandler; ctx.AddJob <TestJobException, TestJobExceptionOptions>( sp => { var options = sp.GetRequiredService <IOptionsMonitor <TestJobExceptionOptions> >(); return(new TestJobException(mockLogger.Object, options)); }, options => { options.CronSchedule = "*/4 * * * * *"; options.RunImmediately = false; options.JobName = jobName; options.RaiseException = true; }, jobName: jobName); }); }); var client = new TestServer(host).CreateClient(); // act var response = await client.GetAsync("/hc"); response.EnsureSuccessStatusCode(); await Task.Delay(TimeSpan.FromSeconds(6)); // assert Assert.Equal("healthy", await response.Content.ReadAsStringAsync()); mockLogger.Verify( l => l.Log( LogLevel.Error, It.IsAny <EventId>(), It.Is <It.IsAnyType>((object v, Type _) => v.ToString() !.Contains(nameof(Exception))), It.IsAny <Exception>(), It.Is <Func <object, Exception, string> >((v, t) => true)), Times.Between(1, 2, Range.Inclusive)); }
public void MustStop() { var configuration = new Mock <IFeatureConfiguration>(); var counter = 0; var list = new List <IFeatureConfiguration> { configuration.Object }; backup.Setup(b => b.GetAllConfigurations()).Returns(list).Callback(() => counter++); sut.Start(); Thread.Sleep(25); sut.Stop(); backup.Verify(b => b.GetAllConfigurations(), Times.Between(counter, counter + 1, Range.Inclusive)); }
public async Task Run_And_Raise_UnobservedTaskException() { // arrange var mockLogger = new Mock <ILogger <TestJobException> >(); var host = CreateHost(services => { services.AddScheduler(ctx => { ctx.UnobservedTaskExceptionHandler = UnobservedTaskExceptionHandler; ctx.AddJob <TestJobException>(_ => { return(new TestJobException(mockLogger.Object, null, true) { RunImmediately = true, CronSchedule = "*/10 * * * * *" }); }); }); // services.AddTransient<ILogger<TestJob>>(x => mockLogger.Object); // short registration without UnobservedTaskExceptionHandler // services.AddSchedulerJob<TestJob,TestJobOptions>(); }); var client = new TestServer(host).CreateClient(); // act var response = await client.GetAsync("/hc"); response.EnsureSuccessStatusCode(); await Task.Delay(TimeSpan.FromSeconds(5)); // assert Assert.Equal("healthy", await response.Content.ReadAsStringAsync()); mockLogger.Verify( l => l.Log( LogLevel.Error, It.IsAny <EventId>(), It.Is <It.IsAnyType>((object v, Type _) => v.ToString().Contains(nameof(Exception))), It.IsAny <Exception>(), It.Is <Func <object, Exception, string> >((v, t) => true)), Times.Between(1, 2, Range.Inclusive)); }
private async Task ShouldCancelPollingTaskWhenReloading() { var expectedKvCalls = 0; var pollingCancelled = new TaskCompletionSource <bool>(); _source.ReloadOnChange = true; _source.Optional = true; _kvEndpoint .Setup(kv => kv.List("Test", It.IsAny <QueryOptions>(), It.IsAny <CancellationToken>())) .Callback <string, QueryOptions, CancellationToken>( (_, __, token) => { if (pollingCancelled.Task.IsCompleted) { return; } expectedKvCalls++; if (token.CanBeCanceled) { token.Register(() => pollingCancelled.TrySetResult(true)); } }) .Returns <string, QueryOptions, CancellationToken>( (_, __, token) => token.IsCancellationRequested ? Task.FromCanceled <QueryResult <KVPair[]> >(token) : Task.Delay(5).ContinueWith(t => new QueryResult <KVPair[]> { StatusCode = HttpStatusCode.OK })); _provider.Load(); // allow polling loop to spin up await Task.Delay(25); _provider.Dispose(); await pollingCancelled.Task; // It's possible that one additional call to KV List endpoint is made depending on when the loop is interrupted. _kvEndpoint.Verify( kv => kv.List("Test", It.IsAny <QueryOptions>(), It.IsAny <CancellationToken>()), Times.Between(expectedKvCalls, expectedKvCalls + 1, Range.Inclusive)); }
public void TryOpenNewCard_CorrectTypeData_ReturnEmptyErrorsList(CardType type) { // Arrange _cardRepositoryMock.Setup(c => c.Add(It.IsAny <Card>())); _cardRepositoryMock.Setup(c => c.Get(_user, It.IsAny <string>())).Returns((Card)null); // Act var(_, errors) = _bankService.TryOpenNewCard(_user, "name", Currency.RUR, type); // Assert _cardRepositoryMock.Verify(c => c.Get(_user, It.IsAny <string>()), Times.Once); _cardNumberGeneratorMock.Verify(c => c.GenerateNewCardNumber(type), Times.Between(1, 2, Range.Inclusive)); _cardRepositoryMock.Verify(c => c.Add(It.IsAny <Card>()), Times.Once); _cardServiceMock.Verify(x => x.TryAddBonusOnOpen(It.IsNotIn(_cards)), Times.Once); _cardRepositoryMock.Verify(c => c.Save(), Times.Once); Assert.Empty(errors); }
internal static void Between_Works() { int min, max; do { min = Tools.Randomizer.Create <int>(); max = Tools.Randomizer.Create <int>(); } while (min >= max); Tools.Asserter.Is(false, Times.Between(min, max).IsInRange(min - 1)); Tools.Asserter.Is(true, Times.Between(min, max).IsInRange(min)); Tools.Asserter.Is(true, Times.Between(min, max).IsInRange(min + 1)); Tools.Asserter.Is(true, Times.Between(min, max).IsInRange(max - 1)); Tools.Asserter.Is(true, Times.Between(min, max).IsInRange(max)); Tools.Asserter.Is(false, Times.Between(min, max).IsInRange(max + 1)); }
public void QuickerVerification() { // Quickly Verify that a mock member was never called _moq.Verify <ILeaf>(x => x.Grow()).Never(); // Or that it was called once _moq.Of <ILeaf>().Object.Grow(); _moq.Verify <ILeaf>(x => x.Grow()).Once(); // Or called X number of times _moq.Of <ILeaf>().Object.Grow(); _moq.Verify <ILeaf>(x => x.Grow()).Times(2); // Or fallback to using the Moq.Times class _moq.Of <ILeaf>().Object.Grow(); _moq.Verify <ILeaf>(x => x.Grow()).Times(Times.AtLeast(3)); _moq.Verify <ILeaf>(x => x.Grow()).Times(Times.Between(3, 7, Range.Inclusive)); }