public void ValidGetAllShouldDisplayAllComments()
        {
            var options = new DbContextOptionsBuilder <ExpensesDbContext>()
                          .UseInMemoryDatabase(databaseName: nameof(ValidGetAllShouldDisplayAllComments))
                          .Options;

            using (var context = new ExpensesDbContext(options))
            {
                var commentsService = new CommentsService(context);

                var added = new Lab2.DTOs.CommentPostDto

                {
                    Text      = "Write a Book",
                    Important = true,
                };
                var added2 = new Lab2.DTOs.CommentPostDto

                {
                    Text      = "Read a Book",
                    Important = false,
                };

                commentsService.Create(added);
                commentsService.Create(added2);

                var result = commentsService.GetAll(string.Empty);
                // Assert.AreEqual(0, result.Count());
            }
        }
Beispiel #2
0
        public void UpsertShouldModifyTheGivenComment()
        {
            var options = new DbContextOptionsBuilder <ExpensesDbContext>()
                          .UseInMemoryDatabase(databaseName: nameof(UpsertShouldModifyTheGivenComment))
                          .Options;

            using (var context = new ExpensesDbContext(options))
            {
                var commentsService = new CommentsService(context);
                var toAdd           = new CommentPostModel()

                {
                    Important = true,
                    Text      = "An important expense",
                };

                var added  = commentsService.Create(toAdd, null);
                var update = new CommentPostModel()
                {
                    Important = false
                };

                var toUp         = commentsService.Create(update, null);
                var updateResult = commentsService.Upsert(added.Id, added);
                Assert.IsNotNull(updateResult);
                Assert.False(toUp.Important);
            }
        }
        public void GetByIdShouldReturnCommentWithCorrectId()
        {
            var options = new DbContextOptionsBuilder <TasksDbContext>()
                          .UseInMemoryDatabase(databaseName: nameof(GetByIdShouldReturnCommentWithCorrectId))
                          .Options;

            using (var context = new TasksDbContext(options))
            {
                var commentsService = new CommentsService(context);
                var toAdd           = new CommentPostDTO()

                {
                    Important = true,
                    Text      = "A nice task...",
                };


                var current  = commentsService.Create(toAdd, null);
                var expected = commentsService.GetById(current.Id);



                Assert.IsNotNull(expected);
                Assert.AreEqual(expected.Text, current.Text);
                Assert.AreEqual(expected.Id, current.Id);
            }
        }
        public void Create_AddsCommentToDb()
        {
            // Arrange
            var context         = this.ServiceProvider.GetRequiredService <WmipDbContext>();
            var commentsService = new CommentsService(context);
            var creationInfo    = new CreateCommentDto
            {
                Body   = "bod",
                Title  = "title",
                PostId = 1,
                UserId = "1"
            };

            // Act
            var result = commentsService.Create(creationInfo, out Comment comment);

            //Assert
            Assert.True(result);
            Assert.Single(context.Comments);
            Assert.NotNull(comment);
            Assert.Equal(creationInfo.Title, comment.Title);
            Assert.Equal(creationInfo.Body, comment.Body);
            Assert.Equal(creationInfo.PostId, comment.CommentedOnId);
            Assert.Equal(creationInfo.UserId, comment.UserId);
        }
        public void UpsertShouldModifyTheGivenComment()
        {
            var options = new DbContextOptionsBuilder <TasksDbContext>()
                          .UseInMemoryDatabase(databaseName: nameof(UpsertShouldModifyTheGivenComment))
                          .Options;

            using (var context = new TasksDbContext(options))
            {
                var commentsService = new CommentsService(context);
                var toAdd           = new CommentPostDTO()

                {
                    Important = true,
                    Text      = "A nice task...",
                };

                var added = commentsService.Create(toAdd, null);
                context.Entry(added).State = EntityState.Detached;

                var update = new Comment()
                {
                    Important = false,
                    Text      = "A nice task...",
                };


                var updateResult = commentsService.Upsert(added.Id, update);
                Assert.NotNull(updateResult);
                Assert.False(updateResult.Important);
                Assert.AreEqual(added.Text, updateResult.Text);
            }
        }
        public void DeleteShouldDeleteAGivenComment()
        {
            var options = new DbContextOptionsBuilder <TasksDbContext>()
                          .UseInMemoryDatabase(databaseName: nameof(DeleteShouldDeleteAGivenComment))
                          .Options;

            using (var context = new TasksDbContext(options))
            {
                var commentsService = new CommentsService(context);
                var toAdd           = new CommentPostDTO()

                {
                    Important = true,
                    Text      = "A nice task...",
                };


                var actual               = commentsService.Create(toAdd, null);
                var afterDelete          = commentsService.Delete(actual.Id);
                int numberOfCommentsInDb = context.Comments.CountAsync().Result;
                var resultComment        = context.Comments.Find(actual.Id);


                Assert.IsNotNull(afterDelete);
                Assert.IsNull(resultComment);
                Assert.AreEqual(0, numberOfCommentsInDb);
            }
        }
        public void Throw_WhenPassedParameterIsNull()
        {
            //Arrange
            var comments        = new Mock <IEfGenericRepository <Comment> >();
            var commentsService = new CommentsService(comments.Object);

            //Act & Assert
            Assert.Throws <ArgumentNullException>(() => commentsService.Create(null));
        }
Beispiel #8
0
        public async void TestDelete()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());
            var repository      = new EfDeletableEntityRepository <Comment>(new ApplicationDbContext(options.Options));
            var commentsService = new CommentsService(repository);
            var userId          = Guid.NewGuid().ToString();
            await commentsService.Create(1, userId, "testContent", 0);

            await commentsService.Create(1, userId, "testContent2", 1);

            AutoMapperConfig.RegisterMappings(typeof(MyTestComment).Assembly);

            await commentsService.Delete(1, 1);

            var commentsCount = commentsService.GetByUserId <MyTestComment>(userId).Count();

            Assert.Equal(0, commentsCount);
        }
 public ActionResult <Blog> Create([FromBody] Comment newComment)
 {
     try
     {
         return(Ok(_commentsService.Create(newComment)));
     }
     catch (System.Exception err)
     {
         return(BadRequest(err));
     }
 }
 public ActionResult <Comment> Create([FromBody] Comment newComment)
 {
     try
     {
         return(Ok(_cos.Create(newComment)));
     }
     catch (System.Exception err)
     {
         return(BadRequest(err.Message));
     }
 }
Beispiel #11
0
        public async Task CreateCommentShouldAddThreeComments()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;
            var dbContext = new ApplicationDbContext(options);

            var repository = new EfDeletableEntityRepository <Comment>(dbContext);
            var service    = new CommentsService(repository);

            var bookId = 3;

            await service.Create(bookId, "Comment's content", "userGruidId1");

            await service.Create(bookId, "Comment's content", "userGruidId2");

            await service.Create(bookId, "Comment's content", "userGruidId3");

            var actualCommentCount = repository.All().Where(c => c.BookId == bookId).Count();

            Assert.Equal(3, actualCommentCount);
        }
        public async Task DeleteShouldBeSuccessfull()
        {
            var options = new DbContextOptionsBuilder <SportsNewsContext>()
                          .UseInMemoryDatabase(databaseName: "CommentsTests")
                          .Options;

            var dbContext = new SportsNewsContext(options);

            var repository      = new DbRepository <Comment>(dbContext);
            var commentsService = new CommentsService(repository);

            await commentsService.Create(1, "1", "dasasd");

            await commentsService.Create(1, "2", "dasasd");

            var id = repository.All().FirstOrDefault().Id;
            await commentsService.Delete(id);

            var count = repository.All().Count();

            Assert.Equal(2, count);
        }
Beispiel #13
0
        public async Task CreateMethodShouldAddCorrectNewCommentToDbAndToArticle()
        {
            var optionsBuilder = new DbContextOptionsBuilder <ApplicationDbContext>()
                                 .UseInMemoryDatabase(Guid.NewGuid().ToString());
            var dbContext = new ApplicationDbContext(optionsBuilder.Options);

            var commentsService = new CommentsService(dbContext);

            var comment = new Comment
            {
                UserUsername = "******",
                Content      = "testContent",
                UserId       = "Icaka99",
            };

            var commentList = new List <Comment>();

            commentList.Add(comment);

            var article = new Article
            {
                Id       = 1,
                Comments = commentList,
            };

            await dbContext.Articles.AddAsync(article);

            var user = new ApplicationUser
            {
                Id       = "Icaka99",
                UserName = "******",
            };

            await dbContext.Users.AddAsync(user);

            var commentToAdd = new CreateCommentInputModel
            {
                ArticleId    = 1,
                PostId       = 1,
                Content      = "testContent",
                UserId       = "Icaka99",
                UserUserName = "******",
            };

            await commentsService.Create(commentToAdd);

            Assert.NotNull(dbContext.Comments.FirstOrDefaultAsync());
            Assert.Equal("testContent", dbContext.Comments.FirstAsync().Result.Content);
            Assert.Equal("Icaka99", dbContext.Comments.FirstAsync().Result.UserId);
            Assert.Equal("Icaka99", dbContext.Comments.FirstAsync().Result.UserUsername);
        }
        public void Create_ReturnsFallOnException()
        {
            // Arrange
            var context                   = this.ServiceProvider.GetRequiredService <WmipDbContext>();
            var commentsService           = new CommentsService(context);
            CreateCommentDto creationInfo = null;

            // Act
            var result = commentsService.Create(creationInfo, out Comment comment);

            //Assert
            Assert.False(result);
            Assert.Null(comment);
        }
        public async Task <ActionResult <Comments> > Post(Comments value)
        {
            System.Diagnostics.Debug.WriteLine("Testing");
            var entity = await _service.Create(value);

            if (entity != null)
            {
                return(Ok(entity));
            }
            else
            {
                return(BadRequest("something broke "));
            }
        }
Beispiel #16
0
        public async Task IsInArticleMethodShouldReturnTrueIfCommentIsInArticle()
        {
            var optionsBuilder = new DbContextOptionsBuilder <ApplicationDbContext>()
                                 .UseInMemoryDatabase(Guid.NewGuid().ToString());
            var dbContext = new ApplicationDbContext(optionsBuilder.Options);

            var commentsService = new CommentsService(dbContext);

            var comment = new Comment
            {
                UserUsername = "******",
                Content      = "testContent",
                UserId       = "Icaka99",
            };

            var commentList = new List <Comment>();

            commentList.Add(comment);

            var article = new Article
            {
                Id       = 1,
                Comments = commentList,
            };

            await dbContext.Articles.AddAsync(article);

            var user = new ApplicationUser
            {
                Id       = "Icaka99",
                UserName = "******",
            };

            await dbContext.Users.AddAsync(user);

            var commentToAdd = new CreateCommentInputModel
            {
                ArticleId    = 1,
                PostId       = 1,
                Content      = "testContent",
                UserId       = "Icaka99",
                UserUserName = "******",
            };

            await commentsService.Create(commentToAdd);

            var result = commentsService.IsInArticle(1, 1);

            Assert.True(result);
        }
        public void InvokeRepositoryMethodAddOnce_WhenPassedParameterIsValid()
        {
            //Arrange
            var comments = new Mock <IEfGenericRepository <Comment> >();
            var comment  = DataHelper.GetComment();

            comments.Setup(x => x.Add(It.IsAny <Comment>())).Verifiable();
            var commentsService = new CommentsService(comments.Object);

            //Act
            commentsService.Create(comment);

            //Assert
            comments.Verify(x => x.Add(It.IsAny <Comment>()), Times.Once);
        }
Beispiel #18
0
 public ActionResult <Comment> Create([FromBody] Comment newComment)
 {
     try
     {
         // req.user.sub || req.userInfo.sub
         string userId = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
         // NOTE DONT TRUST THE USER TO TELL YOU WHO THEY ARE!!!!
         newComment.AuthorId = userId;
         return(Ok(_service.Create(newComment)));
     }
     catch (Exception e)
     {
         return(BadRequest(e.Message));
     }
 }
        public async Task CheckIfCreateWorks()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase("BeatsWaveVirtual").Options;
            var dbContext          = new ApplicationDbContext(options);
            var commentsRepository = new EfDeletableEntityRepository <Comment>(dbContext);

            var service = new CommentsService(commentsRepository);
            await service.Create(1, "asdasd", "lit");

            var result = commentsRepository.All()
                         .FirstOrDefault(x => x.Id == 1);

            Assert.Equal("lit", result.Content);
        }
Beispiel #20
0
        public async Task<ActionResult<Comment>> CreateAsync([FromBody] Comment newComment)
        {
            try
            {
                Profile userInfo = await HttpContext.GetUserInfoAsync<Profile>();
                newComment.CreatorId = userInfo.Id;
                Comment created = _cservice.Create(newComment);

                return Ok(created);
            }
            catch (System.Exception e)
            {
                return BadRequest(e.Message);
            }
        }
Beispiel #21
0
        public async Task <ActionResult <Comment> > Post([FromBody] Comment newComment)
        {
            try
            {
                Profile userInfo = await HttpContext.GetUserInfoAsync <Profile>();

                newComment.CreatorId = userInfo.Id;
                Comment created = _cs.Create(newComment);
                created.Creator = userInfo;
                return(Ok(created));
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
        }
        public async Task CreateComment_WithCorrectData_ShouldSuccessfullyCreate()
        {
            var list = new List <Comment>();

            var mockRepo = new Mock <IDeletableEntityRepository <Comment> >();

            mockRepo.Setup(x => x.All()).Returns(list.AsQueryable());
            mockRepo.Setup(x => x.AddAsync(It.IsAny <Comment>())).Callback((Comment news) => list.Add(news));

            var service = new CommentsService(mockRepo.Object);


            await service.Create(1, "some user", "some text..");

            Assert.Single(list.Where(x => x.UserId == "some user"));
        }
        public async Task Create_WithValidDate_ShouldReturnComment()
        {
            MapperInitializer.InitializeMapper();
            var dbContext = ApplicationDbContextCreatorInMemory.InitializeContext();

            var repository = new EfDeletableEntityRepository <Comment>(dbContext);
            var service    = new CommentsService(repository);

            var comment = service.Create(77, "2", "Hi");

            var result = repository.All().FirstOrDefault(x => x.PostId == 77);

            Assert.Equal(77, result.PostId);
            Assert.Equal("2", result.UserId);
            Assert.Equal("Hi", result.Content);
        }
        public async Task CreateArticleShouldBeSuccessfull()
        {
            var options = new DbContextOptionsBuilder <SportsNewsContext>()
                          .UseInMemoryDatabase(databaseName: "CommentsTests")
                          .Options;

            var dbContext = new SportsNewsContext(options);

            var repository      = new DbRepository <Comment>(dbContext);
            var commentsService = new CommentsService(repository);

            await commentsService.Create(1, "1", "test");

            var count = repository.All().Count();

            Assert.Equal(1, count);
        }
Beispiel #25
0
        public async Task CreateCommentShouldReturnTheRightBookId()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;
            var dbContext = new ApplicationDbContext(options);

            var repository = new EfDeletableEntityRepository <Comment>(dbContext);
            var service    = new CommentsService(repository);

            var bookId = 3;

            await service.Create(bookId, "Comment's content", "userGruidId1");

            var actualBook = await repository.All().FirstOrDefaultAsync();

            Assert.Equal(bookId, actualBook.BookId);
        }
Beispiel #26
0
        public ActionResult Send(string content, int courseItemId)
        {
            bool success = CommentsService.Create(new Comments
            {
                courseItemId = courseItemId,
                content      = content,
                userName     = base.CurrentUser.name
            });

            if (success)
            {
                return(Json(base.RespResult(true, "评论成功,请稍后刷新页面查看!")));
            }
            else
            {
                return(Json(base.RespResult(false, "操作失败,请稍后重试!")));
            }
        }
        public async void Create()
        {
            var mock  = new ServiceMockFacade <ICommentsRepository>();
            var model = new ApiCommentsRequestModel();

            mock.RepositoryMock.Setup(x => x.Create(It.IsAny <Comments>())).Returns(Task.FromResult(new Comments()));
            var service = new CommentsService(mock.LoggerMock.Object,
                                              mock.RepositoryMock.Object,
                                              mock.ModelValidatorMockFactory.CommentsModelValidatorMock.Object,
                                              mock.BOLMapperMockFactory.BOLCommentsMapperMock,
                                              mock.DALMapperMockFactory.DALCommentsMapperMock);

            CreateResponse <ApiCommentsResponseModel> response = await service.Create(model);

            response.Should().NotBeNull();
            mock.ModelValidatorMockFactory.CommentsModelValidatorMock.Verify(x => x.ValidateCreateAsync(It.IsAny <ApiCommentsRequestModel>()));
            mock.RepositoryMock.Verify(x => x.Create(It.IsAny <Comments>()));
        }
        public async Task CreateShouldCreateComment()
        {
            // Arrange
            var db = this.GetDatabase();

            var movie = new Movie()
            {
                Id        = "asdsdfsdf",
                Title     = "titanic",
                Cast      = "Leo",
                StoryLine = "YEY"
            };

            var user = new User()
            {
                Id       = "45ye56rtyh8q92WO3R",
                UserName = "******",
                Email    = "*****@*****.**"
            };

            var model = new CommentBindingModel()
            {
                Title = "I Like this movie",
                Text  = "Its a great movie"
            };

            db.AddRange(movie, user);

            await db.SaveChangesAsync();

            var commentsService = new CommentsService(db);

            // Act
            var result = await commentsService.Create(user, movie, model);

            // Assert
            result.Succeeded
            .Should()
            .Be(true);

            movie.Comments
            .Should()
            .Match(r => r.Any(c => c.Title == model.Title && c.Text == model.Text));
        }
        public void CreateCommentWorksCorrectly()
        {
            var options = new DbContextOptionsBuilder <DealershipDbContext>()
                          .UseInMemoryDatabase(databaseName: "Create_Comment")
                          .Options;

            var db = new DealershipDbContext(options);

            var newsService     = new NewsService(db);
            var commentsService = new CommentsService(db);

            var news = newsService.CreateNews(GetNewsCreateInputModel(), AuthorId);

            var comment = commentsService.Create(AuthorId, news.Id, Content);

            Assert.True(db.News.First().Comments.Count() == 1);
            Assert.True(db.Comments.Count() == 1);
            Assert.True(db.Comments.First().Id == comment.Id);
        }
        public void EditCommentWorksCorrectly()
        {
            var options = new DbContextOptionsBuilder <DealershipDbContext>()
                          .UseInMemoryDatabase(databaseName: "Edit_Comment")
                          .Options;

            var db = new DealershipDbContext(options);

            var commentsService = new CommentsService(db);
            var newsService     = new NewsService(db);

            var news    = newsService.CreateNews(GetNewsCreateInputModel(), AuthorId);
            var comment = commentsService.Create(AuthorId, news.Id, Content);

            Assert.True(comment.Content == Content);

            commentsService.EditComment(comment.Id, "Changed Content!");

            Assert.True(comment.Content == "Changed Content!");
        }