Ejemplo n.º 1
0
        public void Initialize()
        {
            this.mocks = new MockContainer();
            this.mocks.PrepareMocks();

            this.mockContext = new Mock<IUnitOfWorkData>();
            this.mockContext.Setup(c => c.News).Returns(this.mocks.NewsRepositoryMock.Object);

            this.controller = new NewsController(this.mockContext.Object);
            this.controller.Request = new HttpRequestMessage
                {
                    RequestUri = new Uri("http://localhost")
                };
            this.controller.Configuration = new HttpConfiguration();
            this.controller.Configuration.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional });

            this.newsItem = new NewsBindingModel
                {
                    Title = "New News", 
                    Content = "New News Content", 
                    PublishDate = DateTime.Now
                };

            this.fakeNewsCountBefore = this.mockContext.Object.News.GetAll().Count();
        }
        public IHttpActionResult EditNewsById(int id, NewsBindingModel newsBindingModel)
        {
            var news = this.Data.News.GetAll().FirstOrDefault(n => n.Id == id);
            if (news == null)
            {
                return this.NotFound();
            }

            if (newsBindingModel == null)
            {
                return this.BadRequest("News data is missing");
            }

            if (!this.ModelState.IsValid)
            {
                return this.BadRequest(this.ModelState);
            }

            news.Title = newsBindingModel.Title;
            news.Content = newsBindingModel.Content;
            news.PublishDate = newsBindingModel.PublishDate;

            this.Data.SaveChanges();

            var newsView = this.Data.News.GetAll()
                .Where(n => n.Id == news.Id)
                .Select(NewsViewModel.Create())
                .FirstOrDefault();

            return this.Ok(newsView);
        }
Ejemplo n.º 3
0
        public IHttpActionResult UpdateNews(int id, NewsBindingModel newsModel)
        {
            var newsToUpdate = this.NewsData.Find(id);
            if (newsToUpdate == null)
            {
                return this.BadRequest("There is no such news.");
            }

            if (newsToUpdate.UserId != this.UserIdProvider.GetUserId())
            {
                return this.Unauthorized();
            }

            if (newsModel == null || !this.ModelState.IsValid)
            {
                return this.BadRequest("The news title and content are required.");
            }

            newsToUpdate.Title = newsModel.Title;
            newsToUpdate.Content = newsModel.Content;
            if (newsModel.PublishDate != null)
            {
                newsToUpdate.PublishDate = newsModel.PublishDate.Value;
            }

            this.NewsData.Update(newsToUpdate);
            this.NewsData.SaveChanges();

            return this.Ok(newsToUpdate);
        }
        public void Create_News_With_Correct_Data_Should_Return_201Created_Add_News_In_Repo_And_Return_News()
        {
            // Arrange
            var newNews = new NewsBindingModel
            {
                Title = "Title 10",
                Content = "Content 1010101010",
                PublishDate = new DateTime(2015, 9, 1)
            };

            var mockContext = new Mock<INewsData>();
            mockContext.Setup(c => c.News)
                .Returns(this.mock.NewsRepositoryMock.Object);

            var newsController = new NewsController(mockContext.Object);
            this.SetupController(newsController);

            // Act
            var response = newsController.PostNews(newNews)
                .ExecuteAsync(CancellationToken.None).Result;

            // Assert
            var fakeNews = this.mock.NewsRepositoryMock.Object.All().ToList();
            Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);
            mockContext.Verify(c => c.SaveChanges(), Times.Once);
            Assert.AreEqual(6, fakeNews.Count);
            Assert.AreEqual(newNews.Title, fakeNews[5].Title);
            Assert.AreEqual(newNews.Content, fakeNews[5].Content);
            Assert.AreEqual(newNews.PublishDate, fakeNews[5].PublishDate);
        }
        public IHttpActionResult EditNews(int id, NewsBindingModel newsDto)
        {
            if (!this.ModelState.IsValid)
            {
                return this.BadRequest(this.ModelState);
            }

            if (newsDto == null)
            {
                return this.BadRequest(this.ModelState);
            }

            var news = this.Data.Find(id);

            if (news == null)
            {
                return this.NotFound();
            }

            news.Title = newsDto.Title;
            news.Content = newsDto.Content;
            news.PublishedDate = newsDto.PublishedDate;
            this.Data.SaveChanges();

            return this.Ok(new NewsViewModel(news));
        }
        public IHttpActionResult PostNewsItem(NewsBindingModel newsBindingModel)
        {
            if (newsBindingModel == null)
            {
                return this.BadRequest("News data is missing");
            }

            if (!this.ModelState.IsValid)
            {
                return this.BadRequest(this.ModelState);
            }

            var newNews = new NewsItem
                {
                    Title = newsBindingModel.Title, 
                    Content = newsBindingModel.Content, 
                    PublishDate = newsBindingModel.PublishDate
                };

            this.Data.News.Add(newNews);
            this.Data.SaveChanges();

            var newsView = this.Data.News.GetAll()
                .Where(n => n.Id == newNews.Id)
                .Select(NewsViewModel.Create())
                .FirstOrDefault();

            var uriLocation = new
                {
                    controller = "news",
                    id = newNews.Id
                };

            return this.CreatedAtRoute("DefaultApi", uriLocation, newsView);
        }
        public void CreateNewsWithWrongBindingModelShouldReturnBadRequest()
        {
            var controller = new NewsController(this.mock.NewsRepositoryMock.Object);
            this.SetupController(controller);
            var newsBind = new NewsBindingModel();

            controller.ModelState.AddModelError("BadRequest", "Content can't be empty.");
            var response = controller.CreateNews(newsBind).ExecuteAsync(CancellationToken.None).Result;

            Assert.IsNotNull(response);
            Assert.AreEqual(response.StatusCode, HttpStatusCode.BadRequest);
        }
        public void TestAddInvalidNews()
        {
            var controller = new NewsController(repoMock.Object);
            SetupController(controller, "News");

            var invalidNews = new NewsBindingModel { Title = "No content" };

            // it's not the controller's job to validate - there is a validator
            controller.ModelState.AddModelError("Content", "Required");
            var result = controller.AddNews(invalidNews).ExecuteAsync(new CancellationToken()).Result;
            Assert.AreEqual(HttpStatusCode.BadRequest, result.StatusCode);
        }
        public void CreateNewsAddToRepositoryShouldReturnCreated()
        {
            var controller = new NewsController(this.mock.NewsRepositoryMock.Object);
            this.SetupController(controller);
            var newsBind = new NewsBindingModel
                               {
                                   Title = "Some new news", 
                                   Content = "Content", 
                                   PublishedDate = DateTime.Now
                               };

            var response = controller.CreateNews(newsBind).ExecuteAsync(CancellationToken.None).Result;

            Assert.IsNotNull(response);
            Assert.AreEqual(response.StatusCode, HttpStatusCode.Created);
        }
Ejemplo n.º 10
0
        public IHttpActionResult AddNews(NewsBindingModel newsModel)
        {
            if (newsModel == null || !this.ModelState.IsValid)
            {
                return this.BadRequest("The news title and content are required.");
            }

            var newsToAdd = new News
            {
                Title = newsModel.Title,
                Content = newsModel.Content,
                PublishDate = newsModel.PublishDate ?? DateTime.Now,
                UserId = this.UserIdProvider.GetUserId()
            };

            this.NewsData.Add(newsToAdd);
            this.NewsData.SaveChanges();

            return this.CreatedAtRoute("DefaultApi", new { id = newsToAdd.Id }, newsToAdd);
        }
        public void TestAddValidNews()
        {
            var controller = new NewsController(repoMock.Object);
            SetupController(controller, "News");

            var news = new List<News>
            {
                new News { Title = "Zaglavie", Content = "dadadada" },
                new News { Title = "Asdjoqwe", Content = "asodojk" }
            };

            repoMock.Setup(repo => repo.Add(It.IsAny<News>())).Callback((News n) => news.Add(n));

            var newNews = new NewsBindingModel { Title = "Teadsad", Content = "koko6ki" };
            var result = controller.AddNews(newNews).ExecuteAsync(new CancellationToken()).Result;

            Assert.AreEqual(HttpStatusCode.Created, result.StatusCode);
            Assert.AreEqual(newNews.Title, news.Last().Title);
            Assert.AreEqual(newNews.Content, news.Last().Content);
            Assert.IsNotNull(news.Last().PublishDate);
        }
        public void Initialize()
        {
            // Start OWIN testing HTTP server with Web API support
            this.testServer = TestServer.Create(appBuilder =>
                {
                    var config = new HttpConfiguration();
                    WebApiConfig.Register(config);

                    var startup = new Startup();
                    startup.Configuration(appBuilder);

                    appBuilder.UseWebApi(config);
                });

            this.client = this.testServer.HttpClient;

            this.newsItemOne = new NewsBindingModel
                {
                    Title = "News One", 
                    Content = "News One Content", 
                    PublishDate = new DateTime(2015, 09, 11)
                };

            this.newsItemTwo = new NewsBindingModel
            {
                Title = "News Two",
                Content = "News Two Content",
                PublishDate = new DateTime(2015, 09, 10)
            };

            this.invalidNewsItem = new NewsBindingModel
                {
                    Title = null, 
                    Content = "Modified Content", 
                    PublishDate = new DateTime(2015, 09, 09)
                };

            this.PopulateDatabase();
        }
        public IHttpActionResult CreateNews(NewsBindingModel newsDto)
        {
            if (!this.ModelState.IsValid)
            {
                return this.BadRequest(this.ModelState);
            }

            if (newsDto == null)
            {
                return this.BadRequest(this.ModelState);
            }

            var news = new News
                           {
                               Title = newsDto.Title, 
                               Content = newsDto.Content, 
                               PublishedDate = newsDto.PublishedDate ?? DateTime.Now
                           };
            this.Data.Add(news);
            this.Data.SaveChanges();

            return this.CreatedAtRoute("DefaultApi", new { id = news.Id }, news);
        }
        public IHttpActionResult PostNews(NewsBindingModel model)
        {
            if (model == null)
            {
                return this.BadRequest("No news to post.");
            }

            if (!this.ModelState.IsValid)
            {
                return this.BadRequest(this.ModelState);
            }

            var newNews = new News
            {
                Title = model.Title,
                Content = model.Content,
                PublishDate = model.PublishDate
            };

            this.Data.News.Add(newNews);
            this.Data.SaveChanges();

            return this.Created("api/news/" + newNews.Id, newNews);
        }
        public void TestModifyValidNews()
        {
            var controller = new NewsController(repoMock.Object);
            SetupController(controller, "News");

            var news = new News { Id = 18, Title = "Zaglavie", Content = "dadadada" };
            repoMock.Setup(repo => repo.Find(It.IsAny<object>())).Returns(news);

            var updatedNews = new NewsBindingModel { Title = "Zaglavie", Content = "Changed content" };
            var result = controller.UpdateNews(18, updatedNews).ExecuteAsync(new CancellationToken()).Result;
            Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
            var returnedNews = result.Content.ReadAsAsync<News>().Result;
            Assert.AreEqual(updatedNews.Title, returnedNews.Title);
            Assert.AreEqual(updatedNews.Content, returnedNews.Content);
            Assert.AreEqual(news.Title, returnedNews.Title);
        }
        public void Modify_NonExisting_News_Should_Return_400BadRequest()
        {
            // Arrange
            int id = this.GenerateNonExistingId();

            var newNews = new NewsBindingModel
            {
                Title = "Modified title",
                Content = "Modified content",
                PublishDate = new DateTime(2013, 12, 12)
            };

            var mockContext = new Mock<INewsData>();
            mockContext.Setup(c => c.News)
                .Returns(this.mock.NewsRepositoryMock.Object);

            var newsController = new NewsController(mockContext.Object);
            this.SetupController(newsController);

            // Act
            var response = newsController.ChangeNews(id, newNews)
                .ExecuteAsync(CancellationToken.None).Result;

            // Assert
            Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);
            mockContext.Verify(c => c.SaveChanges(), Times.Never);
        }
 private FormUrlEncodedContent GenerateBodyData(NewsBindingModel news)
 {
     var newsBody = new FormUrlEncodedContent(new[]
         {
             new KeyValuePair<string, string>("title", news.Title), 
             new KeyValuePair<string, string>("content", news.Content), 
             new KeyValuePair<string, string>("publishDate", news.PublishDate.ToString(CultureInfo.InvariantCulture))
         });
     return newsBody;
 }
        public void Create_News_With_InCorrect_Data_Should_Return_400BadRequest()
        {
            // Arrange
            var newNews = new NewsBindingModel
            {
                Title = "T", // invalid MinLength
                Content = "Content 1010101010",
                PublishDate = new DateTime(2015, 9, 1)
            };

            var mockContext = new Mock<INewsData>();
            mockContext.Setup(c => c.News)
                .Returns(this.mock.NewsRepositoryMock.Object);

            var newsController = new NewsController(mockContext.Object);
            this.SetupController(newsController);
            newsController.ModelState.AddModelError("Title", "Title MinLength is 5.");

            // Act
            var response = newsController.PostNews(newNews)
                .ExecuteAsync(CancellationToken.None).Result;

            // Assert
            var fakeNews = this.mock.NewsRepositoryMock.Object.All().ToList();
            Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);
            mockContext.Verify(c => c.SaveChanges(), Times.Never);
            Assert.AreEqual(5, fakeNews.Count);
        }
        public void TestModifyInvalidNews()
        {
            var controller = new NewsController(repoMock.Object);
            SetupController(controller, "News");

            var news = new News { Id = 18, Title = "Zaglavie", Content = "dadadada" };
            repoMock.Setup(repo => repo.Find(It.IsAny<object>())).Returns(news);

            var invalidNews = new NewsBindingModel { Content = "No title" };

            // it's not the controller's job to validate - there is a validator
            controller.ModelState.AddModelError("Title", "Required");
            var result = controller.UpdateNews(18, invalidNews).ExecuteAsync(new CancellationToken()).Result;
            Assert.AreEqual(HttpStatusCode.BadRequest, result.StatusCode);
        }
        public void Modify_Existing_News_With_InCorrect_Data_Should_Return_400BadRequest()
        {
            // Arrange
            var fakeNewsToModify = this.mock.NewsRepositoryMock.Object.All().FirstOrDefault();

            var newNews = new NewsBindingModel
            {
                Title = "T", // invalid MinLength
                Content = "Modified content",
                PublishDate = new DateTime(2013, 12, 12)
            };

            var mockContext = new Mock<INewsData>();
            mockContext.Setup(c => c.News)
                .Returns(this.mock.NewsRepositoryMock.Object);

            var newsController = new NewsController(mockContext.Object);
            this.SetupController(newsController);
            newsController.ModelState.AddModelError("Title", "Title MinLength is 5.");

            // Act
            var response = newsController.ChangeNews(fakeNewsToModify.Id, newNews)
                .ExecuteAsync(CancellationToken.None).Result;

            // Assert
            var fakeNews = this.mock.NewsRepositoryMock.Object.All().ToList();
            Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);
            mockContext.Verify(c => c.SaveChanges(), Times.Never);
            Assert.AreEqual(fakeNewsToModify.Title, fakeNews[0].Title);
            Assert.AreEqual(fakeNewsToModify.Content, fakeNews[0].Content);
            Assert.AreEqual(fakeNewsToModify.PublishDate, fakeNews[0].PublishDate);
        }
        public void TestModifyUnexistingNews()
        {
            var controller = new NewsController(repoMock.Object);
            SetupController(controller, "News");

            repoMock.Setup(repo => repo.Find(It.IsAny<object>())).Returns(null as News);

            var updatedNews = new NewsBindingModel { Title = "Zaglavie", Content = "Changed content" };
            var result = controller.UpdateNews(18, updatedNews).ExecuteAsync(new CancellationToken()).Result;
            Assert.AreEqual(HttpStatusCode.BadRequest, result.StatusCode);
        }
        public void ModifyExistingNewsShouldReturnOk()
        {
            var controller = new NewsController(this.mock.NewsRepositoryMock.Object);
            this.SetupController(controller);
            var newsBind = new NewsBindingModel { Title = "Edit", Content = "Edit", PublishedDate = DateTime.Now };

            var response = controller.EditNews(1, newsBind).ExecuteAsync(CancellationToken.None).Result;

            var editedNews = this.mock.NewsRepositoryMock.Object.Find(1);

            Assert.AreEqual(editedNews.Title, "Edit");
            Assert.AreEqual(editedNews.Content, "Edit");
            Assert.AreEqual(response.StatusCode, HttpStatusCode.OK);
        }
        public void Modify_Existing_News_With_Correct_Data_Should_Return_200OK_And_Modify_News_In_Repository()
        {
            // Arrange
            var fakeNewsToModify = this.mock.NewsRepositoryMock.Object.All().FirstOrDefault();

            var newNews = new NewsBindingModel
            {
                Title = "Modified Title",
                Content = "Modified content",
                PublishDate = new DateTime(2013, 12, 12)
            };
            
            var mockContext = new Mock<INewsData>();
            mockContext.Setup(c => c.News)
                .Returns(this.mock.NewsRepositoryMock.Object);

            var newsController = new NewsController(mockContext.Object);
            this.SetupController(newsController);

            // Act
            var response = newsController.ChangeNews(fakeNewsToModify.Id, newNews)
                .ExecuteAsync(CancellationToken.None).Result;

            // Assert
            var fakeNews = this.mock.NewsRepositoryMock.Object.All().ToList();
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            mockContext.Verify(c => c.SaveChanges(), Times.Once);
            Assert.AreEqual(newNews.Title, fakeNews[4].Title);
            Assert.AreEqual(newNews.Content, fakeNews[4].Content);
            Assert.AreEqual(newNews.PublishDate, fakeNews[4].PublishDate);
        }