Exemplo n.º 1
0
        public void When_Create_Returns_CreateView()
        {
            //Given
            _postBuilder.Setup(x => x.BuildCreatePostViewModel()).Returns(new CreatePostViewModel());
            //When
            var result = _postController.Create() as ViewResult;

            //Then
            Assert.AreEqual(String.Empty, result.ViewName);
            Assert.NotNull(result);
            Assert.IsInstanceOf <CreatePostViewModel>(result.Model);
        }
Exemplo n.º 2
0
        public void Create_Test()
        {
            var view = _PostController.Create();

            Assert.NotNull(view);
            Assert.IsType <ViewResult>(view);
        }
Exemplo n.º 3
0
        public void GivenAPostController_WhenICallItsCreateMethod_AndTheModelIsInvalid_ThenItReturnsTheCorrectView()
        {
            var controller = new PostController(_postServiceMock.Object, _dashboardServiceMock, _blogService.Object, null);
            controller.ModelState.AddModelError("Title", "Title error");
            ActionResult result = controller.Create("nickname", new EditPostViewModel());

            Assert.That(result, Is.TypeOf<ViewResult>());
        }
Exemplo n.º 4
0
        public void GivenAPostController_WhenICallItsCreateMethod_AndTheModelIsValid_ThenItReturnsTheCorrectView()
        {
            var controller = new PostController(_postServiceMock.Object, _dashboardServiceMock, _blogService.Object, null);
            var result = controller.Create("nickname", new EditPostViewModel()) as RedirectToRouteResult;

            Assert.That(result, Is.Not.Null);
            Assert.That(result.RouteValues["action"], Is.EqualTo("index").IgnoreCase);
        }
Exemplo n.º 5
0
        public async Task CreateAsync_Post_ModelIsValid_RedirectToIndex()
        {
            Mock <PostService> mock       = new Mock <PostService>();
            PostController     controller = GetNewPostController(mock.Object, null, null);

            RedirectToRouteResult result = (await controller.Create(null)) as RedirectToRouteResult;

            Assert.AreEqual("Index", result.RouteValues["action"]);
        }
Exemplo n.º 6
0
        private void addPost(object sender, EventArgs e)
        {
            var      pName      = postName.Text;
            DateTime pTime      = Convert.ToDateTime(postPublish.Text);
            var      pReadCount = int.Parse(postReadCount.Text);
            var      slctdAut   = Convert.ToInt32(idAuthor.SelectedItem);
            var      slctdCut   = Convert.ToInt32(idCategory.SelectedItem);

            PostController.Create(pName, pTime, pReadCount, slctdAut, slctdCut);
        }
Exemplo n.º 7
0
        public void Create_GetRequestSendsModelToView()
        {
            var repo       = Mock.Create <IPostRepository>();
            var userRepo   = Mock.Create <IUserRepository>();
            var controller = new PostController(repo, userRepo);

            var result = (ViewResult)controller.Create();
            var model  = result.Model;

            Assert.IsTrue(model is Post);
        }
Exemplo n.º 8
0
        public async Task Create_Get_AsksForCreateView()
        {
            Mock <DepartmentService> mock = new Mock <DepartmentService>();

            mock.Setup(m => m.GetAllAsync()).ReturnsAsync(new DepartmentDTO[] { new DepartmentDTO {
                                                                                } });
            PostController controller = GetNewPostController(null, null, mock.Object);

            ViewResult result = (await controller.Create()) as ViewResult;

            Assert.AreEqual("Create", result.ViewName);
        }
        public void createPost()
        {
            Post newPost = new Post {
                Title = "fooTitle"
            };
            var createdResult = controller.Create(newPost);

            // add tests for DB update.
            Assert.NotNull(createdResult);
            Assert.Equal("GetPost", createdResult.RouteName);
            Assert.Equal(newPost.Id, createdResult.RouteValues["Id"]);
        }
Exemplo n.º 10
0
        public void AddNewPost()
        {
            Topic          _topic          = new Topic();
            PostController _postController = new PostController();

            _topic.ID = 1;

            ActionResult result = _postController.Create(new Post());

            Assert.IsNotNull(result);
            Assert.AreEqual(1, _topic.PostCount);
        }
        public void Create_Non_AuthorizedUser_ShouldShowLoginView()
        {
            var mockRepo   = new Mock <IPostRepository>();
            var controller = new PostController(mockRepo.Object)
            {
                ControllerContext = MockHelpers.FakeControllerContext(false)
            };

            var result = controller.Create() as ViewResult;

            Assert.IsNotNull(result);
            Assert.IsNull(result.ViewName);
        }
Exemplo n.º 12
0
        public async Task Create()
        {
            _fixture.AddSampleData();

            using (var context = _fixture.CreateContext()) {
                var controller      = new PostController(_fixture.GetService <IPostService>());
                var postCountBefore = context.Posts.Count();
                var newPost         = _fixture.NewPost.Generate();
                var resultPost      = await controller.Create(newPost);

                Assert.True(resultPost.Id != Guid.Empty && resultPost.Id != null);
                Assert.Equal(postCountBefore + 1, context.Posts.Count());
            }
        }
Exemplo n.º 13
0
        public async Task Create_PostRequestErrorModelState()
        {
            var repo       = Mock.Create <IPostRepository>();
            var userRepo   = Mock.Create <IUserRepository>();
            var controller = new PostController(repo, userRepo);

            controller.ViewData.ModelState.AddModelError("key", "error message");

            var result = (ViewResult)await controller.Create(new Post { Id = "test-id" });

            var model = (Post)result.Model;

            Assert.AreEqual("test-id", model.Id);
        }
Exemplo n.º 14
0
        public async Task Create_PostRequestCallsCreateSendPostToView()
        {
            var repo       = Mock.Create <IPostRepository>();
            var userRepo   = Mock.Create <IUserRepository>();
            var controller = new PostController(repo, userRepo);

            Mock.Arrange(() => repo.Create(Arg.IsAny <Post>()))
            .MustBeCalled();

            var result = await controller.Create(new Post { Id = "test-id" });

            Mock.Assert(repo);
            Assert.IsTrue(result is RedirectToRouteResult);
        }
Exemplo n.º 15
0
        public async Task Create_ShouldReturn_BadRequest_ForInvalidModel()
        {
            var mock       = new Mock <IPostRepository>();
            var controller = new PostController(mock.Object);

            controller.ModelState.AddModelError("error", "erro occured");

            var actionResult = await controller.Create(null);

            Assert.IsNotNull(actionResult);

            BadRequestObjectResult result = actionResult as BadRequestObjectResult;

            Assert.IsNotNull(result);
        }
Exemplo n.º 16
0
        public async Task Create_Post_ModelIsInvalid_AsksForCreateView()
        {
            Mock <PostService> mock = new Mock <PostService>();

            mock.Setup(m => m.CreateAsync(It.IsAny <PostDTO>())).Throws(new ValidationException("", ""));
            Mock <DepartmentService> dmock = new Mock <DepartmentService>();

            dmock.Setup(m => m.GetAllAsync()).ReturnsAsync(new DepartmentDTO[] { new DepartmentDTO {
                                                                                 } });
            PostController controller = GetNewPostController(mock.Object, null, dmock.Object);

            ViewResult result = (await controller.Create(null)) as ViewResult;

            Assert.AreEqual("Create", result.ViewName);
        }
Exemplo n.º 17
0
        public void PostControllerCreate_InvalidPost_ReturnCreateViewWithPost()
        {
            // Arrange
            Mock <IPostLogic> mockPostLogic = new Mock <IPostLogic>();

            mockPostLogic.Setup(x => x.GetAllPosts()).ReturnsAsync(GetPosts());
            var controllerUnderTest = new PostController(_context, mockPostLogic.Object);

            var model = new Post();

            controllerUnderTest.ModelState.AddModelError("error", "Invalid post.");

            // Act
            var result = controllerUnderTest.Create(model);

            // Assert
            var viewResult = Assert.IsType <Task <IActionResult> >(result);
        }
Exemplo n.º 18
0
        public void Cant_Insert_Uncorrect_Post()
        {
            // Arrange
            IPostRepository repository = MockPostRepository.GetRepository(MockPostRepository.STDN);
            PostController  target     = new PostController(repository);
            Post            post       = new Post();

            // Act
            if (!Helpers.IsValidModel <Post>(post))
            {
                target.ModelState.AddModelError("", "");
            }
            ActionResult result = target.Create(post, "#r");

            // Assert
            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(ViewResult));
            MockPostRepository.Mock.Verify(x => x.InsertPost(It.Is <Post>(p => p == post)), Times.Never());
        }
Exemplo n.º 19
0
        public async void Create_Errors()
        {
            PostControllerMockFacade mock = new PostControllerMockFacade();

            var mockResponse = new Mock <CreateResponse <ApiPostResponseModel> >(new FluentValidation.Results.ValidationResult());
            var mockRecord   = new ApiPostResponseModel();

            mockResponse.SetupGet(x => x.Success).Returns(false);

            mock.ServiceMock.Setup(x => x.Create(It.IsAny <ApiPostRequestModel>())).Returns(Task.FromResult <CreateResponse <ApiPostResponseModel> >(mockResponse.Object));
            PostController controller = new PostController(mock.ApiSettingsMoc.Object, mock.LoggerMock.Object, mock.TransactionCoordinatorMock.Object, mock.ServiceMock.Object, mock.ModelMapperMock.Object);

            controller.ControllerContext             = new ControllerContext();
            controller.ControllerContext.HttpContext = new DefaultHttpContext();

            IActionResult response = await controller.Create(new ApiPostRequestModel());

            response.Should().BeOfType <ObjectResult>();
            (response as ObjectResult).StatusCode.Should().Be((int)HttpStatusCode.UnprocessableEntity);
            mock.ServiceMock.Verify(x => x.Create(It.IsAny <ApiPostRequestModel>()));
        }
Exemplo n.º 20
0
        public async Task Create_Post_ModelIsInvalid_RetrievesPostFromModel()
        {
            Mock <PostService> mock = new Mock <PostService>();

            mock.Setup(m => m.CreateAsync(It.IsAny <PostDTO>())).Throws(new ValidationException("", ""));
            Mock <DepartmentService> dmock = new Mock <DepartmentService>();

            dmock.Setup(m => m.GetAllAsync()).ReturnsAsync(new DepartmentDTO[] { new DepartmentDTO {
                                                                                 } });
            PostController controller = GetNewPostController(mock.Object, null, dmock.Object);

            ViewResult result = (await controller.Create(new PostViewModel {
                Id = 2,
                Title = "Programmer"
            })) as ViewResult;

            PostViewModel model = result.ViewData.Model as PostViewModel;

            Assert.AreEqual(2, model.Id);
            Assert.AreEqual("Programmer", model.Title);
        }
Exemplo n.º 21
0
        public async void Create_No_Errors()
        {
            PostControllerMockFacade mock = new PostControllerMockFacade();

            var mockResponse = new CreateResponse <ApiPostResponseModel>(new FluentValidation.Results.ValidationResult());

            mockResponse.SetRecord(new ApiPostResponseModel());
            mock.ServiceMock.Setup(x => x.Create(It.IsAny <ApiPostRequestModel>())).Returns(Task.FromResult <CreateResponse <ApiPostResponseModel> >(mockResponse));
            PostController controller = new PostController(mock.ApiSettingsMoc.Object, mock.LoggerMock.Object, mock.TransactionCoordinatorMock.Object, mock.ServiceMock.Object, mock.ModelMapperMock.Object);

            controller.ControllerContext             = new ControllerContext();
            controller.ControllerContext.HttpContext = new DefaultHttpContext();

            IActionResult response = await controller.Create(new ApiPostRequestModel());

            response.Should().BeOfType <CreatedResult>();
            (response as CreatedResult).StatusCode.Should().Be((int)HttpStatusCode.Created);
            var createResponse = (response as CreatedResult).Value as CreateResponse <ApiPostResponseModel>;

            createResponse.Record.Should().NotBeNull();
            mock.ServiceMock.Verify(x => x.Create(It.IsAny <ApiPostRequestModel>()));
        }
Exemplo n.º 22
0
        public async Task Create_ShouldReturn_CreatedPost()
        {
            const string TEXT = "Unit Test Post goes here...";

            #region Arrange
            int id       = 1;
            var testPost = new Post()
            {
                Id         = 1,
                Text       = TEXT,
                CreatedBy  = "aemloviji",
                InsertDate = DateTime.Now,
            };

            var mockRepo = new Mock <IPostRepository>();
            mockRepo.Setup(repo => repo.Find(id))
            .Returns(Task.FromResult(testPost));
            var controller = new PostController(mockRepo.Object);

            var newPost = new AddOrUpdatePostDTO()
            {
                Text       = TEXT,
                CreatedBy  = "aemloviji",
                InsertDate = DateTime.Now,
            };
            mockRepo.Setup(repo => repo.Add(testPost))
            .Returns(Task.CompletedTask)
            .Verifiable();
            #endregion


            var actionResult = await controller.Create(newPost);

            Assert.IsInstanceOfType(actionResult, typeof(CreatedAtRouteResult));

            var okResult = actionResult as CreatedAtRouteResult;
            Assert.IsInstanceOfType(okResult.Value, typeof(Post));
            Assert.AreEqual(TEXT, (okResult.Value as Post).Text);
        }
        public async Task Create_AuthorizedUser_RedirectActionRedirectsToIndexActionAsync()
        {
            var controller = new PostController(_repository.Object)
            {
                ControllerContext = MockHelpers.FakeControllerContext(false)
            };

            var tempData =
                new TempDataDictionary(controller.ControllerContext.HttpContext, Mock.Of <ITempDataProvider>());

            controller.TempData = tempData;

            var post = new Post()
            {
                Name        = "My post",
                Description = "Description of post"
            };

            var result = Task.FromResult(await controller.Create(post, It.IsAny <int>()) as RedirectToActionResult);

            Assert.IsNotNull(result, "RedirectToIndex needs to redirect to the Index action");
            Assert.AreEqual("Index", result.Result.ActionName);
        }
        public async Task CreateViewIsReturnedWhenInputIsNotValidAsync()
        {
            var post = new Post()
            {
                Name        = "",
                Description = "",
            };
            var controller = new PostController(_repository.Object);

            var validationContext = new ValidationContext(post, null, null);
            var validationResults = new List <ValidationResult>();

            Validator.TryValidateObject(post, validationContext, validationResults, true);
            foreach (var validationResult in validationResults)
            {
                controller.ModelState.AddModelError(validationResult.MemberNames.First(),
                                                    validationResult.ErrorMessage);
            }

            var result = await controller.Create(post, It.IsAny <int>());

            Assert.IsNotNull(Task.FromResult(result));
            Assert.IsTrue(validationResults.Count > 0);
        }
Exemplo n.º 25
0
        public void Can_Insert_Correct_Post()
        {
            // Arrange
            IPostRepository repository = MockPostRepository.GetRepository(MockPostRepository.STDN);
            PostController  target     = new PostController(repository);
            Post            post       = new Post()
            {
                Header    = "h",
                ShortText = "s",
                FullText  = "f"
            };

            // Act
            if (!Helpers.IsValidModel <Post>(post))
            {
                target.ModelState.AddModelError("", "");
            }
            ActionResult result = target.Create(post, "#r");

            // Assert
            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(RedirectResult));
            MockPostRepository.Mock.Verify(x => x.InsertPost(It.Is <Post>(p => p == post)), Times.Once());
        }
Exemplo n.º 26
0
        public void Create_Returns_A_View()
        {
            var result = underTest.Create(1);

            Assert.IsType <ViewResult>(result);
        }
Exemplo n.º 27
0
        public void CreatePostInitialLoadReturnsEmptyView()
        {
            var result = controller.Create();

            Assert.That(result.Model, Is.Null);
        }