public void TestCreateArticleCommand_AuthorNotFound() { var authorId = Guid.NewGuid(); var articleId = Guid.NewGuid(); var heading = ""; var text = "text"; uint year = 2020; Author author = null; var mediator = new Mock <IMediator>(); var articleRepo = new Mock <IArticleRepo>(); var authorRepo = new Mock <IAuthorRepo>(); authorRepo.Setup(x => x.GetById(It.IsAny <Guid>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult(author)); var createCommand = new CreateArticleCommand() { AuthorId = authorId, Heading = heading, Text = text, Year = year }; var handler = new CreateArticleCommand.Handler(articleRepo.Object, authorRepo.Object, mediator.Object); Assert.ThrowsAsync <NotFoundException>(() => handler.Handle(createCommand, new CancellationToken())); }
public void TestCreateArticleCommand() { var authorId = Guid.NewGuid(); var articleId = Guid.NewGuid(); var heading = "heading"; var text = "text"; uint year = 2020; var author = new Author() { Id = authorId, FirstName = "Firstname", LastName = "Lastname" }; var mediator = new Mock <IMediator>(); var articleRepo = new Mock <IArticleRepo>(); articleRepo.Setup(x => x.Save(It.IsAny <Article>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult(new Article(author) { Id = articleId, Heading = heading, Text = text, Year = year, CreatedDate = DateTime.Now })); var authorRepo = new Mock <IAuthorRepo>(); authorRepo.Setup(x => x.GetById(It.IsAny <Guid>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult(author)); var createCommand = new CreateArticleCommand() { AuthorId = authorId, Heading = heading, Text = text, Year = year }; var handler = new CreateArticleCommand.Handler(articleRepo.Object, authorRepo.Object, mediator.Object); Assert.DoesNotThrowAsync(() => handler.Handle(createCommand, new CancellationToken())); }
public async Task TestHandle_WithoutTags_ShouldCreateEntityWithCorrectProperties(string title, string description, string body) { // Arrange var author = new UserProfile(Guid.NewGuid().ToString(), "email", "username"); Context.UserProfiles.Add(author); await Context.SaveChangesAsync(); var command = new CreateArticleCommand { Title = title, Description = description, Body = body }; var currentUser = Mock.Of <ICurrentUserService>(s => s.UserId == author.Id); var sut = new CreateArticleCommand.Handler(currentUser, Context); // Act await sut.Handle(command, CancellationToken.None); var article = await Context.Articles .Include(a => a.Tags) .Include(a => a.Author) .SingleOrDefaultAsync(); // Assert article.Should().NotBeNull(); article.Body.Should().Be(body); article.Description.Should().Be(description); article.Title.Should().Be(title); article.Tags.Should().BeEmpty(); article.Author.Should().BeEquivalentTo(author); }
public async Task Get_ReturnsReview_WhenReviewExistsInTheDatabase() { //Arrange var review = FluentReview.Init.WithData(1, "Test Title", "Reviewer", "ReviewContent"); var article = FluentArticle.Init.WithData(1, "Test Title", "Author", "ArticleContent", DateTime.Now.Date, 5); var articleRequest = new CreateArticleCommand { ArticleContent = article.ArticleContent, Author = article.Author, PublishDate = article.PublishDate.ToString(), StarCount = article.StarCount, Title = article.Title }; await CreateArticleAsync(articleRequest); var reviewRequest = new AddReviewCommand { ArticleId = article.ArticleId, ReviewContent = review.ReviewContent, Reviewer = review.Reviewer }; await AddReviewAsync(reviewRequest); // Act var response = await TestClient.GetAsync("odata/reviews"); // Assert response.StatusCode.Should().Be(HttpStatusCode.OK); var createdReview = await response.Content.ReadAsAsync <OData <FluentReview> >(); createdReview.Value.FirstOrDefault(c => c.ReviewContent == review.ReviewContent).Should().NotBeNull().And.BeEquivalentTo(review); }
public async Task ShouldCreateArticle() { //arrange var loggedUser = await RunAsUserAsync("scott101@localhost", "Pa$$w0rd!"); var articleToCreate = new Faker <ArticleCreateOrEditDto>("en") .RuleFor(a => a.Id, f => f.Random.Guid()) .RuleFor(a => a.Title, f => f.Lorem.Sentence()) .RuleFor(a => a.Abstract, f => f.Lorem.Paragraph()) .RuleFor(a => a.Image, f => null) .RuleFor(a => a.Content, f => f.Lorem.Paragraphs(5)) .Generate(); var command = new CreateArticleCommand(articleToCreate); //act var createdId = await SendAsync(command); var createdArticle = await FindByGuidAsync <Article>(createdId); //assert createdArticle.Id.Should().Be(createdId); createdArticle.Title.Should().Be(articleToCreate.Title); createdArticle.Abstract.Should().Be(articleToCreate.Abstract); createdArticle.Image.Should().BeNull(); createdArticle.Content.Should().Be(articleToCreate.Content); createdArticle.CreatedBy.Should().Be(loggedUser); createdArticle.Created.Should().BeCloseTo(DateTime.UtcNow, 1000); }
public void SetUp() { articleService = new Mock <IArticleService>(); mapper = new Mock <IMapper>(); createArticleCommand = new CreateArticleCommand(articleService.Object, mapper.Object); }
public async Task Create_InvalidObject_ReturnsNull() { //Arrange var testArticles = ArticleList.GetDefaultList(); var articleDbSetMock = testArticles.AsQueryable().BuildMockDbSet(); var dataContextMock = new Mock <CommandDbContext>(); dataContextMock.Setup(m => m.Articles).Returns(articleDbSetMock.Object); var articleRepository = new Mock <IArticleRepository>(); var unitOfWorkMock = new Mock <IUnitOfWork>(); unitOfWorkMock.Setup(uow => uow.ArticleRepository).Returns(articleRepository.Object); var articleForCreation = new ArticleForCreationDto(); var createArticleCommand = new CreateArticleCommand(unitOfWorkMock.Object, _writeMapper); unitOfWorkMock.Setup(uow => uow.Commit()).Returns(Task.FromResult(false)); //Act var result = await createArticleCommand.Execute(articleForCreation); //Assert articleRepository.Verify(r => r.Add(It.IsAny <Article>()), Times.Once); Assert.That(result, Is.Null); }
public async Task Create_ValidObject_ReturnsNewArticle() { //Arrange var unitOfWork = new UnitOfWork(TestContext, new ArticleRepository(TestContext), null); var articleForCreation = new ArticleForCreationDto() { Code = "new code", Name1 = "new name", SupplierId = "sup id", SupplierReference = "sup ref", PurchasePrice = 99.99M, Unit = "ST", PhotoUrl = "www.retail4u.be/newarticle.jpg" }; var createArticleCommand = new CreateArticleCommand(unitOfWork, _writeMapper); var articleCountBefore = TestContext.Articles.Count(); //Act var result = await createArticleCommand.Execute(articleForCreation); //Assert Assert.That(result, Is.Not.Null); Assert.That(result.GetType(), Is.EqualTo(typeof(ArticleForReturnDto))); Assert.That(TestContext.Articles.Count, Is.EqualTo(articleCountBefore + 1)); Assert.That(result.Id, Is.Not.Null); Assert.That(result.Name1, Is.EqualTo(articleForCreation.Name1)); Assert.That(result.Photos, Is.Not.Null); Assert.That(result.Photos.First(), Is.Not.Null); Assert.That(result.Photos.First().Url, Is.EqualTo("www.retail4u.be/newarticle.jpg")); }
public async Task GivenValidCreateRequest_WhenTheUserIsVerified_ReturnsArticleViewModelWithSuccessfulResponse() { // Arrange var createArticleCommand = new CreateArticleCommand { Article = new CreateArticleDto { Title = "Why C# is the Best Language", Description = "It really is!", Body = "I love .NET Core", TagList = new[] { "dotnet", "c#" } } }; var requestContent = await ContentHelper.GetRequestContentWithAuthorization(createArticleCommand, Client); // Act var response = await Client.PostAsync(ArticlesEndpoint, requestContent); var responseContent = await ContentHelper.GetResponseContent <ArticleViewModel>(response); // Assert response.EnsureSuccessStatusCode(); responseContent.ShouldNotBeNull(); responseContent.ShouldBeOfType <ArticleViewModel>(); responseContent.Article.Slug.ShouldBe("why-c-is-the-best-language"); responseContent.Article.Body.ShouldBe(createArticleCommand.Article.Body); responseContent.Article.Title.ShouldBe(createArticleCommand.Article.Title); responseContent.Article.Description.ShouldBe(createArticleCommand.Article.Description); responseContent.Article.TagList.ShouldContain("dotnet"); responseContent.Article.TagList.ShouldContain("c#"); }
public async Task GivenVInvalidCreateRequest_WhenNoTagListItemsAreOnTheRequest_ReturnsUserViewModelWithoutArticleTags() { // Arrange var createArticleCommand = new CreateArticleCommand { Article = new CreateArticleDto { Title = "Why C# is the Best Language", Description = "It really is!", Body = "I love .NET Core" } }; var requestContent = await ContentHelper.GetRequestContentWithAuthorization(createArticleCommand, Client); // Act var response = await Client.PostAsync(ArticlesEndpoint, requestContent); var responseContent = await ContentHelper.GetResponseContent <ArticleViewModel>(response); // Assert // Assert response.EnsureSuccessStatusCode(); responseContent.ShouldNotBeNull(); responseContent.ShouldBeOfType <ArticleViewModel>(); responseContent.Article.Slug.ShouldBe("why-c-is-the-best-language"); responseContent.Article.Body.ShouldBe(createArticleCommand.Article.Body); responseContent.Article.Title.ShouldBe(createArticleCommand.Article.Title); responseContent.Article.Description.ShouldBe(createArticleCommand.Article.Description); responseContent.Article.TagList.ShouldBeEmpty(); }
public async Task CreateArticleCommandTestAsync(string title, string titleImagePath, string identityUserId, int categoryId, bool isPublic, CreateArticleResponse result) { CreateArticleCommand request = new CreateArticleCommand { Title = title, TitleImagePath = titleImagePath, IdentityUserId = identityUserId, CategoryId = categoryId, IsPublic = isPublic, }; CreateArticleCommandHandler handler = new CreateArticleCommandHandler(_createFixture.Context); var expectedResult = await handler.Handle(request, new CancellationToken()); Assert.Equal(expectedResult.IsSuccessful, result.IsSuccessful); if (expectedResult.IsSuccessful) { Article article = await _createFixture.Context.Articles .Include(a => a.TitleImage) .Include(a => a.Creator) .Where(a => a.Id == expectedResult.ArticleId).SingleOrDefaultAsync(); Assert.NotNull(article); Assert.Equal(article.Title, title); Assert.Equal(article.TitleImage.Path, titleImagePath); Assert.Equal(article.Creator.IdentityUserId, identityUserId); Assert.Equal(article.CategoryId, categoryId); Assert.Equal(article.IsPublic, isPublic); } Assert.Equal(expectedResult.Message, result.Message); }
public async Task GivenValidArticleRequest_WhenTheRequestDoesNotContainTagList_ReturnsSuccessfulResponseWithViewModel() { // Arrange var createArticleCommand = new CreateArticleCommand { Article = new CreateArticleDto { Title = "Why C# is the Best Language", Description = "It really is!", Body = "I love .NET Core", } }; // Act var request = new CreateArticleCommandHandler(CurrentUserContext, Context, _logger, Mapper, new DateTimeTest()); var result = await request.Handle(createArticleCommand, CancellationToken.None); // Assert the response model result.ShouldNotBeNull(); result.ShouldBeOfType <ArticleViewModel>(); result.Article.ShouldNotBeNull(); result.Article.Slug.ShouldBe("why-c-is-the-best-language"); result.Article.FavoritesCount.ShouldBe(0); result.Article.TagList.ShouldBeEmpty(); result.Article.Author.Username.ShouldBe(TestConstants.TestUserName); // Assert the article within the DB context var newArticle = Context.Articles.FirstOrDefault(a => string.Equals(a.Slug, result.Article.Slug, StringComparison.OrdinalIgnoreCase)); newArticle.ShouldNotBeNull(); newArticle.Slug.ShouldBe("why-c-is-the-best-language"); newArticle.FavoritesCount.ShouldBe(0); newArticle.Author.Email.ShouldBe(TestConstants.TestUserEmail); Context.ArticleTags.SingleOrDefault(at => at.ArticleId == newArticle.Id)?.ShouldBeNull(); }
protected override void Establish_context() { base.Establish_context(); _validationBag = new ValidationBag(); _command = new CreateArticleCommandTestDataBuilder(); }
public void CreateArticle(CreateArticleCommand command) { var autherId = new UserId(command.AutherId); var id = articleRepository.GenerateId(); var article = new Article(id, command.Title, command.Body, autherId); articleRepository.Save(article); }
public async Task <IActionResult> Post( [FromBody] ArticlePostBody body, CancellationToken ct = default) { var command = new CreateArticleCommand(body.Title, body.Content); var article = await Mediator.Send(command, ct); return(Created($"api/articles/{article.Id}", article)); }
void AndGivenCommandPrepared() { _command = new CreateArticleCommand { UserAccountDataId = _userId, Title = "Example Title", Text = "Example Text" }; }
public async Task <IActionResult> Post([FromBody] ArticleFormModel model, [FromServices] IMapper mapper) { var command = new CreateArticleCommand(CurrentUser); mapper.Map(model, command); var articleId = await Mediator.Send(command); return(Created(await GetArticleById(articleId))); }
public async Task <IActionResult> CreateArticle(ArticleCreateModel model) { var command = new CreateArticleCommand(model.Content, model.Description, model.ImageUrl, model.Language, model.Language, model.Title, model.Type, model.AuthorId); var response = await _mediator.Send(command); return(response.ToActionResult()); }
public ActionResult AddConfirm(ArticleAddModel model) { var createArticle = new CreateArticleCommand(model.Title, model.Body, myId()); articleService.CreateArticle(createArticle); // You shoud return generated id from service or defivary notification object, if you wanna redirect to detail. return(RedirectToAction("MyList")); }
public Task <ResultWrapper <CreateArticleOutput> > Handle(CreateArticleCommand request, CancellationToken cancellationToken) { ResultWrapper <CreateArticleOutput> createArticleResult = new ResultWrapper <CreateArticleOutput>(); try { using (TransactionScope transaction = new TransactionScope(TransactionScopeOption.RequiresNew)) { TArticle tArticle = new TArticle() { Title = request.Title, Content = request.Content, Summary = request.Summary, Image = request.Image, Enabled = request.Enabled, Created = DateTime.Now, }; _dbContext.TArticle.Add(tArticle); _dbContext.SaveChanges(); // Article Sport List <TArticleSport> articleSports = _dbContext.TArticleSport.Where(x => x.TArticle.Id == tArticle.Id).ToList(); _dbContext.TArticleSport.RemoveRange(articleSports.Where(x => !request.Sports.Contains(x.TSportId))); int selectedSportsCount = _dbContext.TSport.Where(x => request.Sports.Contains(x.Id)).Count(); if (selectedSportsCount != request.Sports.Count) { createArticleResult.Status = false; createArticleResult.Message = "Selected sports are invalid!"; return(Task.FromResult(createArticleResult)); } foreach (int SportId in request.Sports.Where(x => !articleSports.Any(z => z.TSportId == x))) { _dbContext.TArticleSport.Add(new TArticleSport() { TArticleId = tArticle.Id, TSportId = SportId }); } _dbContext.SaveChanges(); transaction.Complete(); createArticleResult.Status = true; createArticleResult.Result = new CreateArticleOutput() { Id = tArticle.Id }; } } catch (Exception ex) { createArticleResult.Status = false; createArticleResult.Message = ex.Message; } return(Task.FromResult(createArticleResult)); }
public async Task <IActionResult> CreateArticle([FromBody] CreateArticleCommand command) { var result = await _mediator.Send(command); if (result.ErrorOccurred) { return(BadRequest(result)); } return(Ok(result)); }
public async Task <IActionResult> CreateArticle(string subject, string body) { var request = new CreateArticleCommand(subject, body, Guid.NewGuid()); var isSuccess = await _mediator.Send(request); if (isSuccess) { return(Ok()); } return(BadRequest()); }
public async Task <IActionResult> CreateArticle(CreateArticleDto request) { var command = new CreateArticleCommand(request.Subject, request.Body, Guid.NewGuid()); var isSuccess = await _mediator.Send(command); if (isSuccess) { return(Created(string.Empty, isSuccess)); } return(BadRequest()); }
public void ShouldNotCallHandleIfNotSavedChanges() { context.Setup(x => x.Articles).Returns(dbSetArticle.Object); context.Setup(x => x.SaveChangesAsync(It.IsAny <CancellationToken>())).Returns(Task.FromResult(0)); CreateArticleCommandHandler createArticleCommandHandler = new CreateArticleCommandHandler(context.Object, stringLocalizer.Object, mapper.Object); CreateArticleCommand createArticleCommand = new CreateArticleCommand(); mapper.Setup(x => x.Map <Article>(createArticleCommand)).Returns(new Article()); Func <Task> act = async() => await createArticleCommandHandler.Handle(createArticleCommand, new CancellationToken()); act.Should().Throw <RestException>(); }
public void IsValidShouldBeTrueWhenTitleIsNotNull() { var command = new CreateArticleCommand { Title = "Test Title", Content = "Test Content" }; var validator = new CreateArticleCommandValidator(); var result = validator.Validate(command); result.IsValid.ShouldBe(true); }
public void IsValidShouldBeFalseWhenTitleIsMoreThanFortySymbols() { var command = new CreateArticleCommand { Title = new string('A', 50), Content = "Test Content" }; var validator = new CreateArticleCommandValidator(); var result = validator.Validate(command); result.IsValid.ShouldBe(false); }
public async Task CreateArticleSuccessTest() { //test main branch var sut = new CreateArticleCommandHandler(db); var createArticleCommand = new CreateArticleCommand { Title = newTitleArticle, }; var result = await sut.Handle(createArticleCommand, CancellationToken.None); var createdArticle = db.Articles.Where(u => u.Title == newTitleArticle); Assert.IsType <Unit>(result); Assert.NotNull(createdArticle); }
public static async Task CreateDefaultArticle() { var command = new CreateArticleCommand() { Article = new ArticleBase() { Body = DefaultArticleConstants.Body, Title = DefaultArticleConstants.Title, Description = DefaultArticleConstants.Description, TagList = DefaultArticleConstants.TagList } }; await SliceFixture.ExecuteDbContextAsync(async (ctx, mediator) => { await mediator.Send(command); }); }
public async Task <JsonResult> Post([FromForm] CreateArticle request, CancellationToken token) { var fileStreamResult = Request.Form.Files[0].OpenReadStream(); var fileBytes = new byte[fileStreamResult.Length]; fileStreamResult.Read(fileBytes, 0, (int)fileStreamResult.Length); var requestCommand = new CreateArticleCommand { AuthorId = User.Claims.Single(x => x.Type == "Id").Value, Created = DateTime.UtcNow.ToUniversalTime(), Content = _stringToHtmlHelper.GetHtml(request.Content), Description = request.Description, Title = request.Title, Thumbnail = fileBytes }; return(new JsonResult(new { Article = await _mediator.Send(requestCommand, token) })); }
public void ShouldRequireFieldAndThrowValidationExceptionDuringArticleCreating(string testTitle, string testAbstract, string testContent) { //arrange var command = new CreateArticleCommand() { Id = Guid.NewGuid(), Title = testTitle, Abstract = testAbstract, Image = null, Content = testContent }; //act //assert FluentActions.Invoking(() => SendAsync(command)).Should().Throw <Common.Exceptions.ValidationException>(); }