public void CreateHandler_CreateExpense_VerifyAddExpense() { var token = new CancellationTokenSource().Token; _mockCreateHandler .Setup(c => c.Handle(_createCommand, token)) .Returns(It.IsAny <Task <Unit> >()); _mockMapper .Setup(m => m.Map <ExpenseDTO, Expense>(_createCommand.Expense)) .Returns(_expense); using (var context = new ExpenseTrackerDbContext(_options)) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); _createHandler = new Create.Handler(context, _mockMapper.Object); _createHandler.Handle(_createCommand, token).Wait(); var actual = context.Expenses.CountAsync().Result; Assert.Equal(1, actual); } }
/// <summary> /// creates an article comment based on the given Create command. /// Creates a default user if parameter userName is empty. /// </summary> /// <param name="fixture"></param> /// <param name="command"></param> /// <param name="userName"></param> /// <returns></returns> public static async Task <Domain.Comment> CreateComment(SliceFixture fixture, Create.Command command, string userName) { if (string.IsNullOrWhiteSpace(userName)) { var user = await UserHelpers.CreateDefaultUser(fixture); userName = user.Username; } var dbContext = fixture.GetDbContext(); var currentAccessor = new StubCurrentUserAccessor(userName); var commentCreateHandler = new Create.Handler(dbContext, currentAccessor); var created = await commentCreateHandler.Handle(command, new System.Threading.CancellationToken()); var dbArticleWithComments = await fixture.ExecuteDbContextAsync( db => db.Articles .Include(a => a.Comments).Include(a => a.Author) .Where(a => a.Slug == command.Slug) .SingleOrDefaultAsync() ); var dbComment = dbArticleWithComments.Comments .Where(c => c.ArticleId == dbArticleWithComments.ArticleId && c.Author == dbArticleWithComments.Author) .FirstOrDefault(); return(dbComment); }
public async Task Create_Component_LoggedWithValidInput_Should_CreateComponent() { var fixture = new Fixture(); var mockedContext = new EletronicPartsCatalogContextMock().GetMockedContextWithData(); var mockedCurrentUserAcessor = new Mock <ICurrentUserAccessor>(); mockedCurrentUserAcessor.Setup(mcua => mcua.GetCurrentUsername()).Returns("test"); var sut = new Create.Handler(mockedContext, mockedCurrentUserAcessor.Object); var wheretofinditlist = fixture.Create <string[]>(); var message = new Create.Command { Component = new Create.ComponentData() { Name = "Component", Description = "Description", WhereToFindItList = wheretofinditlist } }; var result = await sut.Handle(message, CancellationToken.None); Assert.Equal(result.Component.Description, message.Component.Description); }
public async Task Create_Project_LoggedWithValidInput_Should_CreateProject() { var fixture = new Fixture(); var mockedContext = new EletronicPartsCatalogContextMock().GetMockedContextWithData(); var mockedCurrentUserAcessor = new Mock <ICurrentUserAccessor>(); mockedCurrentUserAcessor.Setup(mcua => mcua.GetCurrentUsername()).Returns("test"); var sut = new Create.Handler(mockedContext, mockedCurrentUserAcessor.Object); var compentlist = fixture.Create <string[]>(); var taglist = fixture.Create <string[]>(); var message = new Create.Command { Project = new Create.ProjectData { ComponentList = compentlist, Title = "Title", Description = "Description", Body = "Body", TagList = taglist } }; var result = await sut.Handle(message, CancellationToken.None); Assert.Equal(result.Project.Title, message.Project.Title); }
public void Should_Create_License() { var context = GetDbContext(); var modalityId = Guid.NewGuid(); context.Modalities.Add(new Modality { Id = modalityId, Name = "Test Modality" }); context.SaveChanges(); var licenseCreateCommand = new Create.Command { Id = Guid.NewGuid(), Name = "Test License", DisplayName = "TL", ModalityId = modalityId }; var sut = new Create.Handler(context); var result = sut.Handle(licenseCreateCommand, CancellationToken.None).Result; var license = context.Licenses.FirstOrDefault(x => x.ModalityId == modalityId); Assert.NotNull(license); Assert.Equal("Test License", license.Name); }
public void Should_Not_Create_Shift_With_Invalid_Ids() { var context = GetDbContext(); var CreateShiftCommandWithInvalidIds = new Create.Command { Id = Guid.NewGuid(), Start = DateTime.Now, End = DateTime.Now.AddHours(8), TechnologistId = Guid.NewGuid(), ModalityId = Guid.NewGuid(), LicenseId = Guid.NewGuid(), LocationId = Guid.NewGuid(), RoomId = Guid.NewGuid() }; var sut = new Create.Handler(context); var ex = Assert.ThrowsAsync <RestException>(() => sut.Handle(CreateShiftCommandWithInvalidIds, CancellationToken.None)); var errors = (IDictionary <string, object>)ex.Result.Errors; var locationError = errors["location"]; var licenseError = errors["license"]; var roomError = errors["room"]; var modalityError = errors["modality"]; var technologistError = errors["technologist"]; Assert.Equal("Invalid Location", locationError); Assert.Equal("Invalid License", licenseError); Assert.Equal("Invalid Room", roomError); Assert.Equal("Invalid Modality", modalityError); Assert.Equal("Invalid Technologist", technologistError); }
public async Task Create_Project_NotLogged_WithValidInput_ShouldReturn_InvalidOperationException() { var fixture = new Fixture(); var mockedContext = new EletronicPartsCatalogContextMock().GetMockedContextWithData(); var mockedCurrentUserAcessor = new Mock <ICurrentUserAccessor>(); var sut = new Create.Handler(mockedContext, mockedCurrentUserAcessor.Object); var compentlist = fixture.Create <string[]>(); var taglist = fixture.Create <string[]>(); var message = new Create.Command { Project = new Create.ProjectData { ComponentList = compentlist, Title = "Title", Description = "Description", Body = "Body", TagList = taglist } }; await Assert.ThrowsAsync <InvalidOperationException>(() => sut.Handle(message, CancellationToken.None)); }
public void Should_Create_Technologist() { var context = GetDbContext(); var modalityId = Guid.NewGuid(); context.Modalities.Add(new Domain.Modality { Id = modalityId, Name = "Test Modality", DisplayName = "TM" }); context.SaveChanges(); var sut = new Create.Handler(context); var result = sut.Handle(new Create.Command { Id = Guid.NewGuid(), Name = "Test Technologist", ModalityId = modalityId, Initial = "TT", LicenseIdList = new List <Guid> { } } , CancellationToken.None).Result; var technologist = context.Technologists.FirstOrDefault(x => x.ModalityId == modalityId); Assert.NotNull(technologist); Assert.Equal("Test Technologist", technologist.Name); }
public void Should_Fail_With_Invalid_Location() { var context = GetDbContext(); context.Locations.Add(new Location { Id = Guid.NewGuid(), Name = "Location In Db" }); context.SaveChanges(); var CreateCommandInvalidLocationId = new Create.Command { Id = Guid.NewGuid(), Name = "Test Room", LocationId = Guid.NewGuid() }; //act var sut = new Create.Handler(context); var ex = Assert.ThrowsAsync <RestException>(() => sut.Handle(CreateCommandInvalidLocationId, CancellationToken.None)); var thrownError = ex.Result.Errors.ToString(); var expectedError = (new { location = "Could not find location" }).ToString(); Assert.Equal(expectedError, thrownError); }
public void Should_Create_Room() { //arrange var context = GetDbContext(); var locationId = Guid.NewGuid(); var location = new Location { Id = locationId, Name = "LocationForRoomTest" }; context.Locations.Add(location); context.SaveChanges(); var roomId = Guid.NewGuid(); var command = new Create.Command { Id = roomId, Name = "Test Room", LocationId = locationId }; //act var sut = new Create.Handler(context); var result = sut.Handle(command, CancellationToken.None).Result; var room = context.Rooms.FirstOrDefaultAsync(x => x.LocationId == locationId).Result; Assert.NotNull(room); Assert.Equal("Test Room", room.Name); }
public static async Task <ArticleCategoriesEnvelope> ListCategories(SliceFixture fixture, Conduit.Features.ArticleCategories.List.Query command) { // first create the default user var user = await UserHelpers.CreateDefaultUser(fixture); var dbContext = fixture.GetDbContext(); var currentAccessor = new StubCurrentUserAccessor(user.Username); var createCategoryCommand = new Create.Command() { articleCategory = new ArticleCategory() { CategoryId = 1, ArticleId = 1 } }; var categoryCreateHandler = new Create.Handler(dbContext, currentAccessor); var createdCategory = await categoryCreateHandler.Handle(createCategoryCommand, new System.Threading.CancellationToken()); var categoryQueryHandler = new List.QueryHandler(dbContext, currentAccessor); var queriedCategories = await categoryQueryHandler.Handle(command, new System.Threading.CancellationToken()); return(queriedCategories); }
public void SetUp() { var jobCommand = new Create.Command { JobName = "TestJob1", Company = "Netapp", Replication = "Zerto", Servers = "7", LastRun = DateTime.Now, RTA = "10", Results = "OK", Key = "AAAA-BBBB-CCCC-DDDD", RTONeeded = "20", }; var handler = new Create.Handler(testContext); var result = handler.Handle(jobCommand, CancellationToken.None).Result; _jobEditCommand = new Edit.Command { JobName = "TestJob1", Company = "Netapp", Replication = "Zerto", Servers = "7", LastRun = DateTime.Now, RTA = "10", Results = "OK", Key = "AAAA-BBBB-CCCC-DDDD", RTONeeded = "20", }; }
public static async Task <CategoriesEnvelope> ListCategories(SliceFixture fixture, List.Query command) { // first create the default user var user = await UserHelpers.CreateDefaultUser(fixture); var dbContext = fixture.GetDbContext(); var currentAccessor = new StubCurrentUserAccessor(user.Username); var createCategoryCommand = new Create.Command() { Category = new Create.CategoryData() { ParentCategory = 0, Name = "TestCategory", Description = "This is a test Category" } }; var categoryCreateHandler = new Create.Handler(dbContext, currentAccessor); var createdCategory = await categoryCreateHandler.Handle(createCategoryCommand, new System.Threading.CancellationToken()); var categoryQueryHandler = new List.QueryHandler(dbContext, currentAccessor); var queriedCategories = await categoryQueryHandler.Handle(command, new System.Threading.CancellationToken()); return(queriedCategories); }
public void Should_Fail_License_Create_W_Invalid_Modality() { var context = GetDbContext(); context.Modalities.Add(new Modality { Id = Guid.NewGuid(), Name = "Test Modality" }); context.SaveChanges(); var licenseCreateCommand = new Create.Command { Id = Guid.NewGuid(), Name = "Test License", DisplayName = "TL", ModalityId = Guid.NewGuid() }; var sut = new Create.Handler(context); var ex = Assert.ThrowsAsync <RestException>(() => sut.Handle(licenseCreateCommand, CancellationToken.None)); var thrownError = ex.Result.Errors.ToString(); var expectedError = (new { modality = "Modality not found" }).ToString(); Assert.Equal(expectedError, thrownError); }
public void Should_Create_Game() { var userAccessor = new Mock <IUserAccessor>(); var userManager = new Mock <UserManager <Player> >(); var gameCodeGenerator = new Mock <IGameCodeGenerator>(); userAccessor.Setup(u => u.GetCurrentUserName()).Returns("mainplayer"); var context = GetDbContext(); context.Users.AddAsync(new Player { Id = "a", Email = "*****@*****.**", UserName = "******" }); context.SaveChangesAsync(); var gameCommand = new Create.Command { Title = "Game1", MinPoint = "3", MaxPoint = "10" }; var sut = new Create.Handler(context, userAccessor.Object, _mapper, userManager.Object, gameCodeGenerator.Object); var result = sut.Handle(gameCommand, CancellationToken.None).Result; Assert.Equal("Game1", result.Title); }
public CreateTest() { trailsServiceMock = new Mock <ITrailsService>(); userManager = MockHelpers.MockUserManager <User>(); userAccessor = MockHelpers.TestUserAccessor(); trailsServiceMock.Setup(x => x.AddAsync(It.IsAny <Trail>())).ReturnsAsync(true); trailsServiceMock.Setup(t => t.FindByNameAsync(It.IsAny <string>())).ReturnsAsync(TrailsMockData.CreateTrail_US_Mock); userManager.Setup(s => s.FindByIdAsync(It.IsAny <string>())).ReturnsAsync(MockHelpers.MockProUser); createHandler = new Create.Handler(userManager.Object, userAccessor, trailsServiceMock.Object); }
public void CreateJob_WithValidInput_ShouldCreateJob() { //Arrange var handler = new Create.Handler(testContext); //Act var result = handler.Handle(_jobCommand, CancellationToken.None).Result; //Assert Assert.NotNull(result); Assert.That(result.Equals(Unit.Value)); }
public CreateUserHandlerTests() { var users = new[] { new User("sanjay", "*****@*****.**", "sanjay_11", "Sanjay", "Idpuganti") }; _context.Users.AddRange(users); _context.SaveChanges(); var repository = new UserRepository(_context); _handler = new Create.Handler(repository); }
public static async Task <Appointment> CreateAppointment(TestFixture fixture, Create.Command command) { var dbContext = fixture.GetDbContext(); var appointmentCreateHandler = new Create.Handler(dbContext); var created = await appointmentCreateHandler.Handle(command, new CancellationToken()); var dbAppointment = await fixture.ExecuteDbContextAsync(db => db.Appointments .Where(a => a.AppointmentId == created.Appointment.AppointmentId) .SingleOrDefaultAsync()); return(dbAppointment); }
public void CreateJob_WhenJobIdExists_ShouldThrowException() { //Arrange var handler = new Create.Handler(testContext); //Act var result = handler.Handle(_jobCommand, CancellationToken.None).Result; //Assert var ex = Assert.CatchAsync <Exception>(() => handler.Handle(_jobCommand, CancellationToken.None)); if (ex.Equals(typeof(Exception))) { Assert.That(ex.Message, Is.EqualTo("problem saving changes")); } }
public void GivenAnOrderViewOrderDetails() { using var factory = new DbContextFactory <ShopContext>(); var options = factory.CreateOptions(); using var context = factory.CreateContext(options); var createProductHandler = new Features.Products.Create.Handler(context); var foo = createProductHandler.Handle(new Features.Products.Create.Command { Code = "Foo", Description = "Foo description" }, default).Result; var bar = createProductHandler.Handle(new Features.Products.Create.Command { Code = "Bar", Description = "Bar description" }, default).Result; // Create an order var createCommand = new Create.Command { DateCreated = new DateTime(2019, 1, 1), Lines = new List <Create.Command.OrderLine> { new Create.Command.OrderLine { ProductCode = foo, Quantity = 1 }, new Create.Command.OrderLine { ProductCode = bar, Quantity = 3 }, } }; var createHandler = new Create.Handler(context); var orderNumber = createHandler.Handle(createCommand, default).Result; // View order details var query = new Details.Query { Number = orderNumber }; var detailsHandler = new Details.Handler(context); var orderDetails = detailsHandler.Handle(query, default).Result; Assert.AreEqual(createCommand.DateCreated, orderDetails.CreatedDate); Assert.AreEqual(createCommand.Lines.Count(), orderDetails.Lines.Count()); foreach (var(line, index) in orderDetails.Lines.Select((l, i) => (l, i))) { var orderLine = createCommand.Lines.Single(x => x.ProductCode == line.ProductCode); var orderLineNumber = index + 1; Assert.AreEqual(orderLineNumber, line.Number); Assert.AreEqual(orderLine.Quantity, line.Quantity); } }
public static async Task <Domain.Article> CreateArticle(SliceFixture fixture, Create.Command command) { var user = await UserHelpers.CreateDefaultUser(fixture); var dbContext = fixture.GetDbContext(); var currentUserAccessor = new StubCurrentUserAccessor(user.Username); var handler = new Create.Handler(dbContext, currentUserAccessor); var created = await handler.Handle(command, new CancellationToken()); var article = await fixture.ExecuteDbContextAsync(context => context.Articles.Where(a => a.ArticleId == created.Article.ArticleId).SingleOrDefaultAsync()); return(article); }
public static async Task <Domain.ArticleCategory> CreateArticleCategory(SliceFixture fixture, Create.Command command) { // first create the default user var user = await UserHelpers.CreateDefaultUser(fixture); var dbContext = fixture.GetDbContext(); var currentAccessor = new StubCurrentUserAccessor(user.Username); var categoryCreateHandler = new Create.Handler(dbContext, currentAccessor); var created = await categoryCreateHandler.Handle(command, new System.Threading.CancellationToken()); var dbCategory = await fixture.ExecuteDbContextAsync(db => db.ArticleCategories.Where(a => a.ArticleCategoryId == created.ArticleCategoryId) .SingleOrDefaultAsync()); return(dbCategory); }
public async Task Create_Comment_NotLogged_WithValidInput_ShouldReturn_InvalidOperationException() { var mockedContext = new EletronicPartsCatalogContextMock().GetMockedContextWithData(); var mockedCurrentUserAcessor = new Mock <ICurrentUserAccessor>(); var sut = new Create.Handler(mockedContext, mockedCurrentUserAcessor.Object); var message = new Create.Command { Comment = new Create.CommentData() { Body = "Body" } }; await Assert.ThrowsAsync <RestException>(() => sut.Handle(message, CancellationToken.None)); }
public void SetUp() { //first we'll create a new jobaction - as our db is currently empty var jobCommand = new Create.Command { JobName = "TestJob1", Company = "Netapp", Replication = "Zerto", Servers = "7", LastRun = DateTime.Now, RTA = "10", Results = "OK", Key = "AAAA-BBBB-CCCC-DDDD", RTONeeded = "20" }; var handler = new Create.Handler(testContext); var result = handler.Handle(jobCommand, CancellationToken.None).Result; }
public void GivenAnOrderViewOrderOverview() { using var factory = new DbContextFactory <ShopContext>(); var options = factory.CreateOptions(); using var context = factory.CreateContext(options); var createProductHandler = new Features.Products.Create.Handler(context); var foo = createProductHandler.Handle(new Features.Products.Create.Command { Code = "Foo", Description = "Foo description" }, default).Result; var bar = createProductHandler.Handle(new Features.Products.Create.Command { Code = "Bar", Description = "Bar description" }, default).Result; // Create an order var createCommand = new Create.Command { DateCreated = new DateTime(2019, 1, 1), Lines = new List <Create.Command.OrderLine> { new Create.Command.OrderLine { ProductCode = foo, Quantity = 1 }, new Create.Command.OrderLine { ProductCode = bar, Quantity = 3 }, } }; var createHandler = new Create.Handler(context); var orderNumber = createHandler.Handle(createCommand, default).Result; // View order overview var query = new Overview.Query(); var overviewHandler = new Overview.Handler(context); var overviewPage = overviewHandler.Handle(query, default).Result; Assert.AreEqual(1, overviewPage.OrdersTotal); var order = overviewPage.Orders.Single(); Assert.AreEqual(orderNumber, order.Number); }
public async Task Create_User_WithInvalidInput_ShouldReturn_InvalidOperationException() { var mockedContext = new EletronicPartsCatalogContextMock().GetMockedContextWithData(); var mockedHasher = new Mock <IPasswordHasher>(); var mockedJwtTokenGenerator = new Mock <IJwtTokenGenerator>(); var mockedMapper = new Mock <IMapper>(); var sut = new Create.Handler(mockedContext, mockedHasher.Object, mockedJwtTokenGenerator.Object, mockedMapper.Object); var message = new Create.Command { User = new Create.UserData() { Username = "******", Email = "*****@*****.**", Password = "******", PasswordConfirmation = "another pass" } }; await Assert.ThrowsAsync <NullReferenceException>(() => sut.Handle(message, CancellationToken.None)); }
public void Should_Create_Modality() { var context = GetDbContext(); var modalityCreateCommand = new Create.Command { Id = Guid.NewGuid(), Name = "Test Modality", DisplayName = "TM" }; var sut = new Create.Handler(context); var result = sut.Handle(modalityCreateCommand, CancellationToken.None).Result; var newlyCreatedModality = context.Modalities.FirstOrDefaultAsync(x => x.Id == modalityCreateCommand.Id).Result; Assert.NotNull(newlyCreatedModality); Assert.Equal("Test Modality", newlyCreatedModality.Name); Assert.Equal("TM", newlyCreatedModality.DisplayName); }
public async Task CreateBook() { // when Debugging is required, System.Diagnostics.Debugger.Launch(); var options = new DbContextOptionsBuilder <LibraryMaterialContext>() .UseInMemoryDatabase(databaseName: "BookStore") .Options; var context = new LibraryMaterialContext(options); var request = new Create.Execute(); request.Title = "Net Core Micro-services"; request.BookAuthorGuid = Guid.Empty; request.PublishDate = DateTime.Now; var handler = new Create.Handler(context); var result = await handler.Handle(request, new CancellationToken()); Assert.True(result != null); }
public void CreateHandler_CreateExpenseArgsNull_ThrowsArgumentNullException() { var command = new Create.Command { Expense = null }; var token = new CancellationTokenSource().Token; using (var context = new ExpenseTrackerDbContext(_options)) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); _createHandler = new Create.Handler(context, _mockMapper.Object); _mockCreateHandler .Setup(c => c.Handle(command, token)) .Throws <ArgumentNullException>(); Assert.ThrowsAsync <ArgumentNullException>(() => _createHandler.Handle(command, token)); } }