public void Throws_friendly_exception_when_IFindSagas_FindBy_returns_null() { var availableTypes = new List <Type> { typeof(ReturnsNullFinder) }; var messageType = typeof(StartSagaMessage); var messageConventions = new Conventions(); messageConventions.DefineCommandTypeConventions(t => t == messageType); var sagaMetadata = SagaMetadata.Create(typeof(TestSaga), availableTypes, messageConventions); if (!sagaMetadata.TryGetFinder(messageType.FullName, out var finderDefinition)) { throw new Exception("Finder not found"); } var builder = new FakeBuilder(); builder.Register(() => new ReturnsNullFinder()); var customerFinderAdapter = new CustomFinderAdapter <TestSaga.SagaData, StartSagaMessage>(); Assert.That(async() => await customerFinderAdapter.Find(builder, finderDefinition, new InMemorySynchronizedStorageSession(), new ContextBag(), new StartSagaMessage(), new Dictionary <string, string>()), Throws.Exception.With.Message.EqualTo("Return a Task or mark the method as async.")); }
public void CredentialsNotUsedWhenAlreadySet() { var serviceCollection = new ServiceCollection(); var dependencyCredential = GoogleCredential.FromJson(s_serviceAccountJson); serviceCollection.AddSingleton(dependencyCredential); #pragma warning disable CS0618 // Type or member is obsolete Action <FakeBuilder>[] actions = new Action <FakeBuilder>[] { builder => builder.JsonCredentials = "{}", builder => builder.CredentialsPath = "abc", builder => builder.Credential = GoogleCredential.FromJson(s_serviceAccountJson), builder => builder.GoogleCredential = GoogleCredential.FromJson(s_serviceAccountJson), }; #pragma warning restore CS0618 // Type or member is obsolete foreach (var action in actions) { var builder = new FakeBuilder(); action(builder); builder.Configure(serviceCollection); // Note that in one test we'll set the GoogleCredential to a non-null value, but // it won't be the same object. Assert.NotSame(dependencyCredential, builder.GoogleCredential); } }
public void Should_throw_friendly_exception_if_IManageUnitsOfWork_End_returns_null() { var builder = new FakeBuilder(); builder.Register <IManageUnitsOfWork>(() => new UnitOfWorkThatReturnsNullForEnd()); Assert.That(async() => await InvokeBehavior(builder), Throws.Exception.With.Message.EqualTo("Return a Task or mark the method as async.")); }
static void Main(string[] args) { var builder = new FakeBuilder<TestApi>(InjectBadCode, "DoSomething", true); TestApi fakeType = builder.CreateFake(); fakeType.DoApiTest(); Console.ReadLine(); }
public async Task GivenBorrowServiceWhenSetScoreWithUserIsNullThenThrowArgumentNullException() { Borrow borrowDomain = FakeBuilder.GetBorrowFake(); this._mockBorrowRepository.Setup(repo => repo.Get(It.IsAny <int>())) .ReturnsAsync(borrowDomain); int score = 5; ClaimsPrincipal user = null; await Assert.ThrowsAsync <ArgumentNullException>(() => this._borrowService.SetScore(borrowDomain.BorrowId, user, score)); }
public void Configure_MemoryCacheSetAsASingleton() { var builder = new FakeBuilder(); _sut.Configure(builder); var provider = builder.Services.BuildServiceProvider(); Assert.That(provider.GetService <IMemoryCache>(), Is.Not.Null); Assert.That(provider.GetService <IMemoryCache>(), Is.EqualTo(provider.GetService <IMemoryCache>())); }
public async Task GivenProductServiceWhenCreateWithDataValidThenCreateNewProduct() { ProductViewModel model = FakeBuilder.GetProductViewModelFake(0); this.mockUserManager.Setup(mock => mock.FindUserDomain(It.IsAny <ClaimsPrincipal>())) .Returns(Task.FromResult(new User(Guid.NewGuid().ToString()))); await this.productService.Create(new ClaimsPrincipal(), model); this.mockProductRepository.Verify(mock => mock.Save(It.IsAny <Product>()), Times.Once); Assert.True(true); }
public void Should_append_end_exception_to_rethrow() { var builder = new FakeBuilder(); var unitOfWork = new UnitOfWorkThatThrowsFromEnd(); builder.Register <IManageUnitsOfWork>(() => unitOfWork); //since it is a single exception then it will not be an AggregateException Assert.That(async() => await InvokeBehavior(builder), Throws.InvalidOperationException.And.SameAs(unitOfWork.ExceptionThrownFromEnd)); }
public void Should_append_end_exception_to_rethrow() { var builder = new FakeBuilder(); var unitOfWork = new UnitOfWorkThatThrowsFromEnd(); builder.Register<IManageUnitsOfWork>(() => unitOfWork); //since it is a single exception then it will not be an AggregateException Assert.That(async () => await InvokeBehavior(builder), Throws.InvalidOperationException.And.SameAs(unitOfWork.ExceptionThrownFromEnd)); }
public void HttpClientFactory_NotSetBefore() { var factory = new HttpClientFactory(); var serviceCollection = new ServiceCollection(); serviceCollection.AddSingleton <IHttpClientFactory>(factory); var builder = new FakeBuilder(); builder.Configure(serviceCollection); Assert.Same(factory, builder.HttpClientFactory); }
public void CredentialsPrecedence_GoogleCredential() { var credential = GoogleCredential.FromJson(s_serviceAccountJson); var serviceCollection = new ServiceCollection(); serviceCollection.AddSingleton(credential); var builder = new FakeBuilder(); builder.Configure(serviceCollection); Assert.Null(builder.Credential); Assert.Same(credential, builder.GoogleCredential); }
public void Should_call_all_end_even_if_one_or_more_of_them_throws() { var builder = new FakeBuilder(); var unitOfWorkThatThrows = new UnitOfWorkThatThrowsFromEnd(); var unitOfWork = new UnitOfWork(); builder.Register <IManageUnitsOfWork>(unitOfWorkThatThrows, unitOfWork); Assert.That(async() => await InvokeBehavior(builder), Throws.InvalidOperationException); Assert.True(unitOfWork.EndCalled); }
private void btn_Generate_Click(object sender, RoutedEventArgs e) { if (int.TryParse(txt_Quantity.Text, out int count)) { trk_Index.Maximum = count - 1; trk_Index.Value = 0; // For fake logs we need to `Select` the instance property. With other FakeRow implementors it is not necessary. values = FakeBuilder.GenerateMany <FakeLogMessage>(1, 1, (ulong)count).Select(x => x.Instance).ToArray(); txt_Item.Text = ((adata.TypedDoc)values[(int)trk_Index.Value]).ToJsonDataMap().ToString(); } }
public async Task GivenProductServiceWhenGetAllByUserWithUserIsValidAndHaveProductsThenListWithSameNumberProducts() { ClaimsPrincipal user = new ClaimsPrincipal(); List <Product> listProductsDb = FakeBuilder.GetProductsFake(); this.mockProductRepository.Setup(repo => repo.GetAllByUser(It.IsAny <User>())) .ReturnsAsync(listProductsDb); List <ProductViewModel> listProductsModel = await this.productService.GetAllByUser(user); Assert.NotEmpty(listProductsModel); Assert.True(listProductsDb.Count == listProductsModel.Count); }
public async Task GivenBorrowServiceWhenGetAllByLenderWithUserIsValidAndHaveBorrowsThenListWithSameNumberBorrows() { ClaimsPrincipal user = new ClaimsPrincipal(); List <Borrow> listBorrows = FakeBuilder.GetBorrowsFake(); this._mockBorrowRepository.Setup(repo => repo.GetAllByLender(It.IsAny <User>())) .ReturnsAsync(listBorrows); List <BorrowViewModel> listBorrowModel = await this._borrowService.GetAllByLender(user); Assert.NotEmpty(listBorrowModel); Assert.True(listBorrows.Count == listBorrowModel.Count); }
public void Should_pass_exception_to_cleanup() { var builder = new FakeBuilder(); var unitOfWork = new CaptureExceptionPassedToEndUnitOfWork(); var throwingUoW = new UnitOfWorkThatThrowsFromEnd(); builder.Register <IManageUnitsOfWork>(unitOfWork, throwingUoW); //since it is a single exception then it will not be an AggregateException Assert.That(async() => await InvokeBehavior(builder), Throws.InstanceOf <InvalidOperationException>().And.SameAs(throwingUoW.ExceptionThrownFromEnd)); Assert.AreSame(throwingUoW.ExceptionThrownFromEnd, unitOfWork.Exception); }
public void Should_pass_exceptions_to_the_uow_end() { var builder = new FakeBuilder(); var unitOfWork = new UnitOfWork(); builder.Register<IManageUnitsOfWork>(() => unitOfWork); var ex = new Exception("Handler failed"); //since it is a single exception then it will not be an AggregateException Assert.That(async () => await InvokeBehavior(builder, ex), Throws.InstanceOf<Exception>().And.SameAs(ex)); Assert.AreSame(ex, unitOfWork.ExceptionPassedToEnd); }
public async Task Should_not_call_Begin_or_End_when_hasUnitsOfWork_is_false() { var builder = new FakeBuilder(); var unitOfWork = new UnitOfWork(); builder.Register <IManageUnitsOfWork>(unitOfWork); await InvokeBehavior(builder, hasUnitsOfWork : false); Assert.IsFalse(unitOfWork.BeginCalled); Assert.IsFalse(unitOfWork.EndCalled); }
public async Task Should_not_call_Begin_or_End_when_hasUnitsOfWork_is_false() { var builder = new FakeBuilder(); var unitOfWork = new UnitOfWork(); builder.Register<IManageUnitsOfWork>(unitOfWork); await InvokeBehavior(builder, hasUnitsOfWork: false); Assert.IsFalse(unitOfWork.BeginCalled); Assert.IsFalse(unitOfWork.EndCalled); }
public void Should_not_invoke_end_if_begin_was_not_invoked() { var builder = new FakeBuilder(); var unitOfWorkThatThrowsFromBegin = new UnitOfWorkThatThrowsFromBegin(); var unitOfWork = new UnitOfWork(); builder.Register <IManageUnitsOfWork>(unitOfWorkThatThrowsFromBegin, unitOfWork); //since it is a single exception then it will not be an AggregateException Assert.That(async() => await InvokeBehavior(builder), Throws.InvalidOperationException); Assert.False(unitOfWork.EndCalled); }
public void Should_pass_exceptions_to_the_uow_end() { var builder = new FakeBuilder(); var unitOfWork = new UnitOfWork(); builder.Register <IManageUnitsOfWork>(() => unitOfWork); var ex = new Exception("Handler failed"); //since it is a single exception then it will not be an AggregateException Assert.That(async() => await InvokeBehavior(builder, ex), Throws.InstanceOf <Exception>().And.SameAs(ex)); Assert.AreSame(ex, unitOfWork.ExceptionPassedToEnd); }
public async Task GivenProductServiceWhenDeletePhotoWithPhotoNotFoundThenThrowArgumentException() { Product productDb = FakeBuilder.GetProductFake(); productDb.AddPhotos(new List <string>() { "url1", "url2" }); this.mockProductRepository.Setup(mock => mock.Get(It.IsAny <int>())).ReturnsAsync(productDb); await Assert.ThrowsAsync <PhotoNotFoundException>(() => this.productService.DeletePhoto(1, 3)); this.mockProductRepository.Verify(mock => mock.Save(It.IsAny <Product>()), Times.Never); }
public async Task GivenBorrowServiceWhenCreateWithDataValidThenCreateNewBorrow() { int productId = 0; BorrowViewModel model = FakeBuilder.GetBorrowViewModelFake(0, productId); this._mockUserManager.Setup(mock => mock.FindUserDomain(It.IsAny <ClaimsPrincipal>())) .Returns(Task.FromResult(new User(Guid.NewGuid().ToString()))); this._mockProductRepository.Setup(mock => mock.Get(It.IsAny <int>())) .Returns(Task.FromResult(FakeBuilder.GetProductFake())); await this._borrowService.Create(new ClaimsPrincipal(), model); this._mockBorrowRepository.Verify(mock => mock.Save(It.IsAny <Borrow>()), Times.Once); Assert.True(true); }
public void Should_not_invoke_end_if_begin_was_not_invoked() { var builder = new FakeBuilder(); var unitOfWorkThatThrowsFromBegin = new UnitOfWorkThatThrowsFromBegin(); var unitOfWork = new UnitOfWork(); builder.Register<IManageUnitsOfWork>(unitOfWorkThatThrowsFromBegin, unitOfWork); //since it is a single exception then it will not be an AggregateException Assert.That(async () => await InvokeBehavior(builder), Throws.InvalidOperationException); Assert.False(unitOfWork.EndCalled); }
public async Task GivenBorrowServiceWhenCloseWithBorrowFoundAndCreatedThenStatusInvalidException() { Borrow borrowDomain = FakeBuilder.GetBorrowFake(); Assert.True(borrowDomain.Status == BorrowStatus.Created); this._mockBorrowRepository.Setup(repo => repo.Get(It.IsAny <int>())) .ReturnsAsync(borrowDomain); await Assert.ThrowsAsync <StatusInvalidException>(() => this._borrowService.Close(borrowDomain.BorrowId)); this._mockBorrowRepository.Verify(mock => mock.Save(It.IsAny <Borrow>()), Times.Never); }
public void HttpClientFactory_SetBefore() { var manual = new HttpClientFactory(); var dependency = new HttpClientFactory(); var serviceCollection = new ServiceCollection(); serviceCollection.AddSingleton <IHttpClientFactory>(dependency); var builder = new FakeBuilder { HttpClientFactory = manual }; builder.Configure(serviceCollection); Assert.Same(manual, builder.HttpClientFactory); }
public async Task GivenProductServiceWhenDeleteWithProductIdWithProductFoundThenDeleteOk() { Product productDb = FakeBuilder.GetProductFake(); productDb.AddPhotos(new List <string>() { "url1", "url2" }); this.mockProductRepository.Setup(mock => mock.Get(It.IsAny <int>())).ReturnsAsync(productDb); await this.productService.Delete(1); this.mockProductRepository.Verify(mock => mock.Delete(It.IsAny <Product>()), Times.Once); }
public async Task GivenBorrowServiceWhenRejectWithBorrowFoundAndCreatedThenIsUpdated() { Borrow borrowDomain = FakeBuilder.GetBorrowFake(); Assert.True(borrowDomain.Status == BorrowStatus.Created); this._mockBorrowRepository.Setup(repo => repo.Get(It.IsAny <int>())) .ReturnsAsync(borrowDomain); await this._borrowService.Reject(borrowDomain.BorrowId); this._mockBorrowRepository.Verify(mock => mock.Save(It.IsAny <Borrow>()), Times.Once); Assert.True(borrowDomain.Status == BorrowStatus.Rejected); }
public async Task GetBooks_ReturnsBooks() { var fakeBooks = FakeBuilder.CreateMany <Book>().ToList(); BookRepositoryMock.Setup(r => r.Get()).ReturnsAsync(fakeBooks); var expectedResult = fakeBooks.ToRepresentation(); var result = await Controller.Get(); Assert.IsNotNull(result); Assert.IsInstanceOf <OkNegotiatedContentResult <ICollection <BookRepresentation> > >(result); var resultContent = ((OkNegotiatedContentResult <ICollection <BookRepresentation> >)result).Content; Assert.AreEqual(resultContent, expectedResult.ToList()); }
public async Task GivenBorrowServiceWhenAddCommentWithUserIsNullThenThrowArgumentNullException() { Borrow borrowDomain = FakeBuilder.GetBorrowFake(); this._mockBorrowRepository.Setup(repo => repo.Get(It.IsAny <int>())) .ReturnsAsync(borrowDomain); string comment = "aaaa"; ClaimsPrincipal user = null; await Assert .ThrowsAsync <ArgumentNullException>(() => this._borrowService.AddComment(borrowDomain.BorrowId, comment, user)); this._mockBorrowRepository .Verify(mock => mock.Save(It.IsAny <Borrow>()), Times.Never); }
public async Task GivenProductServiceWhenChangeStatusThenChangeStatusOk() { Product productDb = FakeBuilder.GetProductFake(); this.mockProductRepository.Setup(mock => mock.Get(It.IsAny <int>())).ReturnsAsync(productDb); Assert.True(productDb.IsShary()); await this.productService.ChangeStatus(productDb.ProductId); this.mockProductRepository.Verify(mock => mock.Save(It.IsAny <Product>()), Times.Once); Assert.True(productDb.IsUnshary()); await this.productService.ChangeStatus(productDb.ProductId); this.mockProductRepository.Verify(mock => mock.Save(It.IsAny <Product>()), Times.Exactly(2)); Assert.True(productDb.IsShary()); }
public void Configure_CanResolveBoundTypes() { var builder = new FakeBuilder(); _sut.Configure(builder); var provider = builder.Services.BuildServiceProvider(); Assert.That(provider.GetService <Configuration>(), Is.Not.Null); Assert.That(provider.GetService <IUrlHelper>(), Is.Not.Null); Assert.That(provider.GetService <ILocationRepository>(), Is.Not.Null); Assert.That(provider.GetService <ILocationFinder>(), Is.Not.Null); Assert.That(provider.GetService <LocationCollection>(), Is.Not.Null); Assert.That(provider.GetService <IMemoryCache>(), Is.Not.Null); Assert.That(provider.GetService <IImageGenerator>(), Is.Not.Null); }
public void When_first_throw_second_is_cleaned_up() { var builder = new FakeBuilder(); var unitOfWorkThatThrowsFromEnd = new UnitOfWorkThatThrowsFromEnd(); var unitOfWork = new UnitOfWork(); builder.Register <IManageUnitsOfWork>(unitOfWorkThatThrowsFromEnd, unitOfWork); //since it is a single exception then it will not be an AggregateException Assert.That(async() => await InvokeBehavior(builder), Throws.InvalidOperationException); Assert.IsTrue(unitOfWorkThatThrowsFromEnd.BeginCalled); Assert.IsTrue(unitOfWorkThatThrowsFromEnd.EndCalled); Assert.IsTrue(unitOfWork.BeginCalled); Assert.IsTrue(unitOfWork.EndCalled); }
public void Should_invoke_ends_on_all_begins_that_was_called_even_when_begin_throws() { var builder = new FakeBuilder(); var normalUnitOfWork = new UnitOfWork(); var unitOfWorkThatThrows = new UnitOfWorkThatThrowsFromBegin(); var unitOfWorkThatIsNeverCalled = new UnitOfWork(); builder.Register <IManageUnitsOfWork>(normalUnitOfWork, unitOfWorkThatThrows, unitOfWorkThatIsNeverCalled); Assert.That(async() => await InvokeBehavior(builder), Throws.InvalidOperationException); Assert.True(normalUnitOfWork.EndCalled); Assert.True(unitOfWorkThatThrows.EndCalled); Assert.False(unitOfWorkThatIsNeverCalled.EndCalled); }
public void When_first_throw_second_is_cleaned_up() { var builder = new FakeBuilder(); var unitOfWorkThatThrowsFromEnd = new UnitOfWorkThatThrowsFromEnd(); var unitOfWork = new UnitOfWork(); builder.Register<IManageUnitsOfWork>(unitOfWorkThatThrowsFromEnd, unitOfWork); //since it is a single exception then it will not be an AggregateException Assert.That(async () => await InvokeBehavior(builder), Throws.InvalidOperationException); Assert.IsTrue(unitOfWorkThatThrowsFromEnd.BeginCalled); Assert.IsTrue(unitOfWorkThatThrowsFromEnd.EndCalled); Assert.IsTrue(unitOfWork.BeginCalled); Assert.IsTrue(unitOfWork.EndCalled); }
static Task InvokeBehavior(FakeBuilder builder, Exception toThrow = null) { var runner = new UnitOfWorkBehavior(); var context = new TestableIncomingPhysicalMessageContext(); context.Builder = builder; return(runner.Invoke(context, ctx => { if (toThrow != null) { throw toThrow; } return TaskEx.CompletedTask; })); }
public void Should_call_all_end_even_if_one_or_more_of_them_throws() { var builder = new FakeBuilder(); var unitOfWorkThatThrows = new UnitOfWorkThatThrowsFromEnd(); var unitOfWork = new UnitOfWork(); builder.Register<IManageUnitsOfWork>(unitOfWorkThatThrows, unitOfWork); Assert.That(async () => await InvokeBehavior(builder), Throws.InvalidOperationException); Assert.True(unitOfWork.EndCalled); }
public async Task Should_invoke_ends_in_reverse_order_of_the_begins() { var builder = new FakeBuilder(); var order = new List<string>(); var firstUnitOfWork = new OrderAwareUnitOfWork("first", order); var secondUnitOfWork = new OrderAwareUnitOfWork("second", order); builder.Register<IManageUnitsOfWork>(firstUnitOfWork, secondUnitOfWork); await InvokeBehavior(builder); Assert.AreEqual("first", order[0]); Assert.AreEqual("second", order[1]); Assert.AreEqual("second", order[2]); Assert.AreEqual("first", order[3]); }
public void Should_invoke_ends_on_all_begins_that_was_called_even_when_begin_throws() { var builder = new FakeBuilder(); var normalUnitOfWork = new UnitOfWork(); var unitOfWorkThatThrows = new UnitOfWorkThatThrowsFromBegin(); var unitOfWorkThatIsNeverCalled = new UnitOfWork(); builder.Register<IManageUnitsOfWork>(normalUnitOfWork, unitOfWorkThatThrows, unitOfWorkThatIsNeverCalled); Assert.That(async () => await InvokeBehavior(builder), Throws.InvalidOperationException); Assert.True(normalUnitOfWork.EndCalled); Assert.True(unitOfWorkThatThrows.EndCalled); Assert.False(unitOfWorkThatIsNeverCalled.EndCalled); }
public async Task Verify_order() { var builder = new FakeBuilder(); var unitOfWork1 = new CountingUnitOfWork(); var unitOfWork2 = new CountingUnitOfWork(); var unitOfWork3 = new CountingUnitOfWork(); builder.Register<IManageUnitsOfWork>(unitOfWork1, unitOfWork2, unitOfWork3); await InvokeBehavior(builder); Assert.AreEqual(1, unitOfWork1.BeginCallIndex); Assert.AreEqual(2, unitOfWork2.BeginCallIndex); Assert.AreEqual(3, unitOfWork3.BeginCallIndex); Assert.AreEqual(3, unitOfWork1.EndCallIndex); Assert.AreEqual(2, unitOfWork2.EndCallIndex); Assert.AreEqual(1, unitOfWork3.EndCallIndex); }
static Task InvokeBehavior(FakeBuilder builder, Exception toThrow = null, bool hasUnitsOfWork = true) { var runner = new UnitOfWorkBehavior(hasUnitsOfWork); var context = new TestableIncomingPhysicalMessageContext(); context.Builder = builder; return runner.Invoke(context, ctx => { if (toThrow != null) { throw toThrow; } return TaskEx.CompletedTask; }); }
public void Should_throw_friendly_exception_if_IManageUnitsOfWork_End_returns_null() { var builder = new FakeBuilder(); builder.Register<IManageUnitsOfWork>(() => new UnitOfWorkThatReturnsNullForEnd()); Assert.That(async () => await InvokeBehavior(builder), Throws.Exception.With.Message.EqualTo("Return a Task or mark the method as async.")); }
public void Should_pass_exception_to_cleanup() { var builder = new FakeBuilder(); var unitOfWork = new CaptureExceptionPassedToEndUnitOfWork(); var throwingUoW = new UnitOfWorkThatThrowsFromEnd(); builder.Register<IManageUnitsOfWork>(unitOfWork, throwingUoW); //since it is a single exception then it will not be an AggregateException Assert.That(async () => await InvokeBehavior(builder), Throws.InstanceOf<InvalidOperationException>().And.SameAs(throwingUoW.ExceptionThrownFromEnd)); Assert.AreSame(throwingUoW.ExceptionThrownFromEnd, unitOfWork.Exception); }