コード例 #1
0
        public async Task CreatePost_ReturnsViewResult_WhenModelStateIsInvalid()
        {
            Console.WriteLine("Running test: CreatePost_ReturnsViewResult_WhenModelStateIsInvalid");
            // Arrange
            var mockRepo = new Mock <IThoughtwaveRepository>();

            mockRepo
            .Setup(repo => repo.GetAllThoughtsAsync())
            .Returns(Task.FromResult(GetTestThoughts()));
            var mapper     = GetMapper();
            var controller = new ThoughtsController(null, null, null, mapper, new LoggerFactory());

            controller.ModelState.AddModelError("Title", "Required");
            var newThought = new CreateThoughtViewModel();

            // Act
            var result = await controller.Create(newThought);

            // Assert
            var viewResult = Assert.IsType <ViewResult>(result);

            Assert.IsType <CreateThoughtViewModel>(viewResult.Model);
        }
コード例 #2
0
        public async Task <IActionResult> Create(CreateThoughtViewModel model)
        {
            if (ModelState.IsValid)
            {
                var thought = _mapper.Map <Thought>(model);

                // Save associated Thought author
                thought.Author = await GetCurrentUserAsync();

                // set thought image
                var imagePath = await UploadImage(HttpContext.Request.Form.Files);

                if (imagePath != null)
                {
                    thought.Image = imagePath;
                }

                // Save to the database
                _repository.AddThoughtAsync(thought);

                if (await _repository.CommitChangesAsync())
                {
                    var thoughtUrl = GetThoughtUrl(thought);
                    TempData["success"] = "Your new Thought has been created";
                    return(Redirect(thoughtUrl));
                }
                else
                {
                    _logger.LogError($"Issue saving thought: {thought.Title} by {thought.Author.UserName}");
                    TempData["error"] = "There was an issue creating your new Thought";
                    return(RedirectToAction("Manage"));
                }
            }

            // issue with model state
            return(View(model));
        }