예제 #1
0
        public async Task <ActionResult> Put(Guid id, [FromBody] UserDtoUpdate dtoUpdate)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                var result = await _service.Get(id);

                if (result == null)
                {
                    return(NotFound());
                }

                if (!result.Id.Equals(dtoUpdate.Id))
                {
                    return(StatusCode((int)HttpStatusCode.BadRequest, "Id nao informado."));
                }

                var validaton = await _service.Validation(dtoUpdate, id);

                if (!validaton.Sucess)
                {
                    return(StatusCode((int)HttpStatusCode.Found, validaton.Message));
                }

                return(Ok(await _service.Put(dtoUpdate)));
            }
            catch (ArgumentException e)
            {
                return(StatusCode((int)HttpStatusCode.InternalServerError, e.Message));
            }
        }
        public async Task Erro_Ao_Invocar_A_Controller_Update()
        {
            var serviceMock = new Mock <IUserService>();
            var nome        = Faker.Name.FullName();
            var email       = Faker.Internet.Email();

            serviceMock.Setup(m => m.Put(It.IsAny <Guid>(), It.IsAny <UserDtoUpdate>())).ReturnsAsync(
                new UserDtoUpdateResult
            {
                Id       = Guid.NewGuid(),
                Email    = email,
                Name     = nome,
                UpdateAt = DateTime.UtcNow,
            }
                );

            _controller = new UsersController(serviceMock.Object);
            _controller.ModelState.AddModelError("Email", "Email é um campo obrigatório");
            Mock <IUrlHelper> url = new Mock <IUrlHelper>();

            _controller.Url = url.Object;
            var userDtoUpdate = new UserDtoUpdate
            {
                Email = email,
                Name  = nome,
            };

            var result = await _controller.Put(Guid.NewGuid(), userDtoUpdate);

            Assert.True(result is BadRequestObjectResult);
            Assert.False(_controller.ModelState.IsValid);
        }
예제 #3
0
        public async Task E_Possivel_Invocar_A_Controller_Updated()
        {
            var serviceMock = new Mock <IUserService>();
            var name        = Faker.Name.FullName();
            var email       = Faker.Internet.Email();

            serviceMock.Setup(m => m.Put(It.IsAny <UserDtoUpdate>())).ReturnsAsync(
                new UserDtoUpdateResult
            {
                Id       = Guid.NewGuid(),
                Name     = name,
                Email    = email,
                UpdateAt = DateTime.UtcNow,
            }
                );

            _controller = new UsersController(serviceMock.Object);

            var userDtoUpdate = new UserDtoUpdate
            {
                Id    = Guid.NewGuid(),
                Name  = name,
                Email = email,
            };

            var result = await _controller.Put(userDtoUpdate);

            Assert.True(result is OkObjectResult);

            var resultValue = ((OkObjectResult)result).Value as UserDtoUpdateResult;

            Assert.NotNull(resultValue);
            Assert.Equal(userDtoUpdate.Name, resultValue.Name);
            Assert.Equal(userDtoUpdate.Email, resultValue.Email);
        }
예제 #4
0
        public async Task <ActionResult> Put([FromBody] UserDtoUpdate user)
        {
            try
            {
                if (!await service.Exist(user.Id))
                {
                    return(NotFound(false.AsNotFoundResponse("Usuário não encontrado.")));
                }
                if (!user.Email.IsEmail())
                {
                    return(UnprocessableEntity(false.AsUnprocessableResponse("Por favor entre com um e-mail válido.")));
                }

                if (!await service.IsValidEmail(user.Email, user.Id))
                {
                    return(Conflict(false.AsConflictResponse("E-mail já cadastrado.")));
                }

                if (await service.Put(user) == null)
                {
                    return(BadRequest());
                }
                return(Ok(true.AsSuccessResponse("Usuário alterado com sucesso.")));
            }
            catch (ArgumentException e)
            {
                return(StatusCode((int)HttpStatusCode.InternalServerError, e.Message));
            }
        }
예제 #5
0
        public async Task <ActionResult> Put([FromBody] UserDtoUpdate user)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                UserDtoUpdateResult result = await _service.Put(user);

                if (result == null)
                {
                    return(BadRequest());
                }

                ResponseBase <UserDtoUpdateResult> responseBase = new ResponseBase <UserDtoUpdateResult>();
                responseBase.Message = "Usuário alterado com sucesso!";
                responseBase.Success = true;
                responseBase.Result  = result;


                return(Ok(responseBase));
            }
            catch (ArgumentException e)
            {
                return(StatusCode((int)HttpStatusCode.InternalServerError, e.Message));
            }
        }
예제 #6
0
        public async Task It_Is_Possible_To_Invoke_The_Controller_Update()
        {
            var serviceMock = new Mock <IUserService>();
            var name        = Faker.Name.FullName();
            var email       = Faker.Internet.Email();

            serviceMock.Setup(s => s.Put(It.IsAny <UserDtoUpdate>())).ReturnsAsync(
                new UserDtoUpdateResult
            {
                Id        = Guid.NewGuid(),
                Name      = name,
                Email     = email,
                UpdatedAt = DateTime.Now
            });

            _controller = new UsersController(serviceMock.Object);
            _controller.ModelState.AddModelError("Email", "Email é obrigatório.");

            var userDtoUpdate = new UserDtoUpdate
            {
                Id    = Guid.NewGuid(),
                Name  = name,
                Email = email
            };

            var result = await _controller.Put(userDtoUpdate);

            Assert.True(result is BadRequestObjectResult);
        }
예제 #7
0
        public async Task E_Possivel_Invocar_a_UsersController_Update_Retornando_BadRequest()
        {
            var serviceMock = new Mock <IUserService>();
            var name        = Name.FullName();
            var email       = Internet.Email();

            serviceMock.Setup(m => m.Put(It.IsAny <UserDtoUpdate>())).ReturnsAsync(
                new UserDtoUpdateResult
            {
                Id       = Guid.NewGuid(),
                Name     = name,
                Email    = email,
                CreateAt = DateTime.UtcNow
            });

            _controller = new UsersController(serviceMock.Object);
            _controller.ModelState.AddModelError("Name", "É um campo Obrigatório");

            Mock <IUrlHelper> url = new Mock <IUrlHelper>();

            url.Setup(x => x.Link(It.IsAny <string>(), It.IsAny <Object>())).Returns("http://localhost:5000");
            _controller.Url = url.Object;

            var userDtoUpdate = new UserDtoUpdate
            {
                Name  = name,
                Email = email,
            };

            var result = await _controller.Put(userDtoUpdate);

            Assert.True(result is BadRequestObjectResult);
            Assert.False(_controller.ModelState.IsValid);
        }
예제 #8
0
        public async Task <UserDtoUpdateResult> Put(UserDtoUpdate user)
        {
            var entity = _mapper.Map <UserEntity>(user);
            var result = await _repository.UpdateAsync(entity);

            return(_mapper.Map <UserDtoUpdateResult>(result));
        }
예제 #9
0
        public async Task <ActionResult> Put([FromBody] UserDtoUpdate user)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                var result = await _service.Put(user);

                if (result == null)
                {
                    return(BadRequest());
                }
                else
                {
                    return(Ok(result));
                }
            }
            catch (ArgumentException ex)
            {
                return(StatusCode((int)HttpStatusCode.InternalServerError, ex.Message));

                throw;
            }
        }
        public async Task PutCreate()
        {
            var serviceMock = new Mock <IUserService>();
            var nome        = Faker.Name.FullName();
            var email       = Faker.Internet.Email();

            serviceMock.Setup(m => m.Put(It.IsAny <UserDtoUpdate>())).ReturnsAsync(
                new UserDtoUpdateResult
            {
                Id       = Guid.NewGuid(),
                Name     = nome,
                Email    = email,
                UpdateAt = DateTime.UtcNow
            }
                );

            _controller = new UsersController(serviceMock.Object);
            _controller.ModelState.AddModelError("Email", "É um campo obrigatório");

            var UserDtoUpdate = new UserDtoUpdate
            {
                Id    = Guid.NewGuid(),
                Name  = nome,
                Email = email
            };

            var result = await _controller.Put(UserDtoUpdate);

            Assert.True(result is BadRequestObjectResult);
            Assert.False(_controller.ModelState.IsValid);
        }
예제 #11
0
        public async Task <UserDtoUpdateResult> Put(UserDtoUpdate user)
        {
            var model  = _mapper.Map <UserModel>(user);
            var entity = _mapper.Map <UserEntity>(model);

            return(_mapper.Map <UserDtoUpdateResult>(await _repository.UpdateAsync(entity)));
        }
예제 #12
0
        public async Task <UserDtoUpdateResult> Put(UserDtoUpdate user)
        {
            UserModel  model  = _mapper.Map <UserModel>(user);
            UserEntity entity = _mapper.Map <UserEntity>(model);
            UserEntity result = await _repository.UpdateAsync(entity);

            return(_mapper.Map <UserDtoUpdateResult>(result));
        }
예제 #13
0
        public async Task <UserDtoUpdateResult> Put(UserDtoUpdate user)
        {
            var model  = mapper.Map <UserModel>(user);
            var entity = mapper.Map <UserEntity>(model);
            var result = await repository.UpdateAsync(entity);

            return(mapper.Map <UserDtoUpdateResult>(result));
        }
        public async Task <UserDtoUpdateResult> Put(UserDtoUpdate user)
        {
            var model  = _mapper.Map <UserModel>(user); //não precisaria mas o DDD se for necessário alguma valiação precisa...
            var entity = _mapper.Map <UserEntity>(model);
            var result = await _repository.UpdateAsync(entity);

            return(_mapper.Map <UserDtoUpdateResult>(result));
        }
예제 #15
0
        public TestUsers()
        {
            FakerId    = Faker.RandomNumber.Next();
            FakerName  = Faker.Name.FullName();
            FakerEmail = Faker.Internet.Email();

            FakerNameUpdated  = Faker.Name.FullName();
            FakerEmailUpdated = Faker.Internet.Email();

            for (int index = 0; index < 10; index++)
            {
                var dto = new UserDto()
                {
                    Id    = Faker.RandomNumber.Next(),
                    Name  = Faker.Name.FullName(),
                    Email = Faker.Internet.Email()
                };

                FakerUserDtoList.Add(dto);
            }

            FakerUserDto = new UserDto()
            {
                Id    = FakerId,
                Name  = FakerName,
                Email = FakerEmail
            };

            FakerUserDtoCreate = new UserDtoCreate()
            {
                Name  = FakerName,
                Email = FakerEmail
            };

            FakerUserDtoCreateResult = new UserDtoCreateResult()
            {
                Id       = FakerId,
                Name     = FakerName,
                Email    = FakerEmail,
                CreateAt = DateTime.UtcNow
            };

            FakerUserDtoUpdate = new UserDtoUpdate()
            {
                Id    = FakerId,
                Name  = FakerName,
                Email = FakerEmail
            };

            FakerUserDtoUpdateResult = new UserDtoUpdateResult()
            {
                Id       = FakerId,
                Name     = FakerName,
                Email    = FakerEmail,
                UpdateAt = DateTime.UtcNow
            };
        }
예제 #16
0
        public UserTest()
        {
            UserId           = Guid.NewGuid();
            UserName         = Faker.Name.FullName();
            UserEmail        = Faker.Internet.Email();
            UserNameChanged  = Faker.Name.FullName();
            UserEmailChanged = Faker.Internet.Email();

            for (int i = 0; i < 10; i++)
            {
                var dto = new UserDto()
                {
                    Id    = Guid.NewGuid(),
                    Nome  = Faker.Name.FullName(),
                    Email = Faker.Internet.Email()
                };

                UserList.Add(dto);
            }

            userDto = new UserDto
            {
                Id   = UserId,
                Nome = UserName
            };

            userDtoCreate = new UserDtoCreate
            {
                Nome  = UserName,
                Email = UserEmail
            };

            userDtoCreateResult = new UserDtoCreateResult
            {
                Id       = UserId,
                Nome     = UserName,
                Email    = UserEmail,
                CreateAt = DateTime.UtcNow
            };

            userDtoUpdate = new UserDtoUpdate
            {
                Id    = UserId,
                Nome  = UserName,
                Email = UserEmail
            };


            userDtoUpdateResult = new UserDtoUpdateResult
            {
                Id       = UserId,
                Nome     = UserName,
                Email    = UserEmail,
                CreateAt = DateTime.UtcNow
            };
        }
예제 #17
0
        public UsuarioTestes()
        {
            IdUsuario            = Guid.NewGuid();
            NomeUsuario          = Faker.Name.FullName();
            EmailUsuario         = Faker.Internet.Email();
            NomeUsuarioAlterado  = Faker.Name.FullName();
            EmailUsuarioAlterado = Faker.Internet.Email();

            for (int i = 0; i < 10; i++)
            {
                var dto = new UserDto()
                {
                    Id    = Guid.NewGuid(),
                    Name  = Faker.Name.FullName(),
                    Email = Faker.Internet.Email()
                };
                listaUserDto.Add(dto);
            }

            userDto = new UserDto
            {
                Id    = IdUsuario,
                Name  = NomeUsuario,
                Email = EmailUsuario
            };

            userDtoCreate = new UserDtoCreate
            {
                Name  = NomeUsuario,
                Email = EmailUsuario
            };


            userDtoCreateResult = new UserDtoCreateResult
            {
                Id       = IdUsuario,
                Name     = NomeUsuario,
                Email    = EmailUsuario,
                CreateAt = DateTime.UtcNow
            };

            userDtoUpdate = new UserDtoUpdate
            {
                Id    = IdUsuario,
                Name  = NomeUsuarioAlterado,
                Email = EmailUsuarioAlterado
            };

            userDtoUpdateResult = new UserDtoUpdateResult
            {
                Id       = IdUsuario,
                Name     = NomeUsuarioAlterado,
                Email    = EmailUsuarioAlterado,
                UpdateAt = DateTime.UtcNow
            };
        }
예제 #18
0
        public UserTest()
        {
            IdUser          = Guid.NewGuid();
            NomeUser        = Faker.Name.FullName();
            EmailUser       = Faker.Internet.Email();
            NomeUserUpdate  = Faker.Name.FullName();
            EmailUserUpdate = Faker.Internet.Email();

            for (int i = 0; i < 10; i++)
            {
                var Dto = new UserDto()
                {
                    Id    = Guid.NewGuid(),
                    Name  = Faker.Name.FullName(),
                    Email = Faker.Internet.Email(),
                };
                listaDto.Add(Dto);
            }

            userDto = new UserDto
            {
                Id    = IdUser,
                Name  = NomeUser,
                Email = EmailUser
            };

            userDtoCreate = new UserDtoCreate
            {
                Name  = NomeUser,
                Email = EmailUser,
            };

            userDtoCreateResult = new UserDtoCreateResult
            {
                Id       = IdUser,
                Name     = NomeUser,
                Email    = EmailUser,
                CreateAt = DateTime.UtcNow
            };

            userDtoUpdate = new UserDtoUpdate
            {
                Id    = IdUser,
                Name  = NomeUserUpdate,
                Email = EmailUserUpdate,
            };

            userDtoUpdateResult = new UserDtoUpdateResult
            {
                Id       = IdUser,
                Name     = NomeUserUpdate,
                Email    = EmailUserUpdate,
                UpdateAt = DateTime.UtcNow
            };
        }
예제 #19
0
        public UserTestes()
        {
            IdUser         = Guid.NewGuid();
            EmailUser      = Faker.Internet.Email();
            AlterEmailUser = Faker.Internet.Email();
            NameUser       = Faker.Name.FullName();
            AlterNameUser  = Faker.Name.FullName();

            for (int i = 0; i < 10; i++)
            {
                var dto = new UserDto()
                {
                    Id    = Guid.NewGuid(),
                    Name  = Faker.Name.FullName(),
                    Email = Faker.Internet.Email(),
                };
                listUserDto.Add(dto);
            }

            userDto = new UserDto()
            {
                Id    = IdUser,
                Name  = NameUser,
                Email = EmailUser
            };

            userDtoCreate = new UserDtoCreate()
            {
                Name  = NameUser,
                Email = EmailUser
            };


            userDtoCreateResult = new UserDtoCreateResult()
            {
                Id       = IdUser,
                Name     = NameUser,
                Email    = EmailUser,
                CreateAt = DateTime.UtcNow
            };

            userDtoUpdate = new UserDtoUpdate()
            {
                Name  = NameUser,
                Email = EmailUser
            };

            userDtoUpdateResult = new UserDtoUpdateResult()
            {
                Id       = IdUser,
                Name     = NameUser,
                Email    = EmailUser,
                UpdateAt = DateTime.UtcNow
            };
        }
예제 #20
0
        public UserTests()
        {
            UserId           = Guid.NewGuid();
            UserName         = Faker.Name.FullName();
            UserEmail        = Faker.Internet.Email();
            UserNameUpdated  = Faker.Name.FullName();
            UserEmailUpdated = Faker.Internet.Email();

            for (int i = 0; i < 10; i++)
            {
                userDtos.Add(new UserDto()
                {
                    Id    = Guid.NewGuid(),
                    Name  = Faker.Name.FullName(),
                    Email = Faker.Internet.Email()
                });
            }

            userDto = new UserDto()
            {
                Id    = UserId,
                Name  = UserName,
                Email = UserEmail
            };

            userDtoCreate = new UserDtoCreate()
            {
                Name  = UserName,
                Email = UserEmail
            };

            userDtoCreateResult = new UserDtoCreateResult()
            {
                Id        = UserId,
                Name      = UserName,
                Email     = UserEmail,
                CreatedAt = DateTime.Now
            };

            userDtoUpdate = new UserDtoUpdate()
            {
                Id    = UserId,
                Name  = UserNameUpdated,
                Email = UserEmailUpdated
            };

            userDtoUpdateResult = new UserDtoUpdateResult()
            {
                Id        = UserId,
                Name      = UserNameUpdated,
                Email     = UserEmailUpdated,
                UpdatedAt = DateTime.Now
            };
        }
예제 #21
0
        public async Task <UserDtoUpdateResult> Put(Guid id, UserDtoUpdate item)
        {
            var model        = _mapper.Map <UserModel>(item);
            var entity       = _mapper.Map <UserEntity>(model);
            var Userpassword = await _repository.SelectAsync(id);

            entity.Password = Userpassword.Password;
            var result = await _repository.UpdasteAsync(id, entity);

            return(_mapper.Map <UserDtoUpdateResult>(result));
        }
예제 #22
0
        public async Task <IActionResult> UpdateUser([FromForm] UserDtoUpdate userDto)
        {
            var user = await _userManager.GetUserAsync(User);

            user.LastName  = userDto.LastName;
            user.FirstName = userDto.FirstName;
            user.Ext       = userDto.Ext;

            if (userDto.Avatar != null & userDto.Avatar.Length > 0)
            {
                using var ms = new MemoryStream();
                userDto.Avatar.CopyTo(ms);
                var fileBytes = ms.ToArray();
                user.Avatar = fileBytes;
            }

            if (!await _userManager.CheckPasswordAsync(user, userDto.OldPassword))
            {
                return(Conflict());
            }

            var tokenEmail = await _userManager.GenerateChangeEmailTokenAsync(user, userDto.Email);

            var tokenPhone = await _userManager.GenerateChangePhoneNumberTokenAsync(user, userDto.Phone);

            await _userManager.ChangeEmailAsync(user, userDto.Email, tokenEmail);

            await _userManager.ChangePhoneNumberAsync(user, userDto.Phone, tokenPhone);

            if (!string.IsNullOrEmpty(userDto.NewPassword))
            {
                await _userManager.ChangePasswordAsync(user, userDto.NewPassword, userDto.OldPassword);
            }

            var userUpdateResult = await _userManager.UpdateAsync(user);

            if (userUpdateResult.Succeeded)
            {
                _logger.LogInformation("User updated");
                return(NoContent());
            }
            _logger.LogError("Imposible to register " + user.Email);
            return(Problem(userUpdateResult.Errors.First().Description, null, 500));
        }
        public async Task <ActionResult> Put([FromBody] UserDtoUpdate user)
        {
            try
            {
                var result = await _service.Put(user);

                if (result != null)
                {
                    return(Ok(result));
                }
                else
                {
                    return(BadRequest());
                }
            }
            catch (ArgumentException ex)
            {
                return(this.StatusCode(StatusCodes.Status500InternalServerError, $"Database Failed {ex.Message}"));
            }
        }
예제 #24
0
        public async Task E_Possivel_Invocar_a_UsersController_Update_Retornando_OK()
        {
            var serviceMock = new Mock <IUserService>();
            var name        = Name.FullName();
            var email       = Internet.Email();

            serviceMock.Setup(m => m.Put(It.IsAny <UserDtoUpdate>())).ReturnsAsync(
                new UserDtoUpdateResult
            {
                Id       = Guid.NewGuid(),
                Name     = name,
                Email    = email,
                UpdateAt = DateTime.UtcNow
            });

            _controller = new UsersController(serviceMock.Object);

            Mock <IUrlHelper> url = new Mock <IUrlHelper>();

            url.Setup(x => x.Link(It.IsAny <string>(), It.IsAny <Object>())).Returns("http://localhost:5000");
            _controller.Url = url.Object;

            var userDtoUpdate = new UserDtoUpdate
            {
                Name  = name,
                Email = email,
            };

            var result = await _controller.Put(userDtoUpdate);

            Assert.True(result is OkObjectResult);

            var resultValue = ((OkObjectResult)result).Value as UserDtoUpdateResult;

            Assert.NotNull(resultValue);
            Assert.Equal(userDtoUpdate.Name, resultValue.Name);
            Assert.Equal(userDtoUpdate.Email, resultValue.Email);
            Assert.True(resultValue.UpdateAt != null);
        }
예제 #25
0
        public async Task UpdateTest()
        {
            var serviceMock = new Mock <IUserService>();
            var name        = Faker.Name.FullName();
            var email       = Faker.Internet.Email();

            serviceMock.Setup(m => m.Put(It.IsAny <UserDtoUpdate>())).ReturnsAsync(
                new UserDtoUpdateResult
            {
                Id       = Guid.NewGuid(),
                Name     = name,
                Email    = email,
                UpdateAt = DateTime.UtcNow
            }
                );

            _controller = new UsersController(serviceMock.Object);

            var userDtoUpdate = new UserDtoUpdate
            {
                Id    = Guid.NewGuid(),
                Name  = name,
                Email = email
            };

            var result = await _controller.Put(userDtoUpdate);

            var resultValue = ((OkObjectResult)result).Value as UserDtoUpdateResult;

            //Assert.True(result is OkObjectResult);
            //Assert.NotNull(resultValue);
            //Assert.Equal(userDtoUpdate.Name, resultValue.Name);
            //Assert.Equal(userDtoUpdate.Email, resultValue.Email);

            result.Should().BeOfType <OkObjectResult>();
            resultValue.Should().NotBeNull();
            resultValue.Name.Should().Equals(userDtoUpdate.Name);
            resultValue.Email.Should().Equals(userDtoUpdate.Email);
        }
예제 #26
0
        public async Task Execute_Update()
        {
            var serviceMock = new Mock <IUserService>();
            var nome        = Faker.Name.FullName();
            var email       = Faker.Internet.Email();

            serviceMock.Setup(m => m.Put(It.IsAny <UserDtoUpdate>())).ReturnsAsync(new UserDtoUpdateResult
            {
                Id       = Guid.NewGuid(),
                Name     = nome,
                Email    = email,
                CreateAt = DateTime.Now
            });

            _controller = new UsersController(serviceMock.Object);
            //_controller.ModelState.AddModelError("Name", "É um campo obrigatório");

            Mock <IUrlHelper> url = new Mock <IUrlHelper>();

            url.Setup(x => x.Link(It.IsAny <string>(), It.IsAny <object>())).Returns("http://localhost:5000");
            _controller.Url = url.Object;

            var userDtoUpdate = new UserDtoUpdate
            {
                Id    = Guid.NewGuid(),
                Name  = nome,
                Email = email
            };

            var result = await _controller.Put(userDtoUpdate.Id, userDtoUpdate);

            var resultValue = ((OkObjectResult)result).Value as UserDtoUpdateResult;

            Assert.True(result is OkObjectResult);
            Assert.True(_controller.ModelState.IsValid);
            Assert.Equal(userDtoUpdate.Name, resultValue.Name);
            //Assert.True(result is BadRequestResult);
        }
예제 #27
0
        public async Task <ActionResult> Put(Guid id, [FromBody] UserDtoUpdate user)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            try
            {
                var result = await _service.Put(id, user);

                if (result != null)
                {
                    //return Created(new Uri(Url.Link("GetWithId"), new { id = result.Id })), result);
                    return(Created(new Uri(Url.Link("GetWithId", new { id = result.Id })), result));
                }

                return(BadRequest());
            }
            catch (ArgumentException e)
            {
                return(StatusCode((int)HttpStatusCode.InternalServerError, e.Message));
            }
        }
        public async Task <ActionResult> UpdateUser([FromBody] UserDtoUpdate user)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                var result = await _userService.UpdateUser(user);

                if (result != null)
                {
                    return(Ok(result));
                }

                return(BadRequest());
            }
            catch (ArgumentException argumentException)
            {
                return(StatusCode((int)HttpStatusCode.InternalServerError, argumentException.Message));
            }
        }
        public async Task E_Possivel_Realizar_Crud_Usuario()
        {
            await AdicionarToken();

            _name  = Faker.Name.First();
            _email = Faker.Internet.Email();

            var userDto = new UserDtoCreate()
            {
                Name  = _name,
                Email = _email
            };

            //Post
            var response = await PostJsonAsync(userDto, $"{hostApi}users/post", client);

            var postResult = await response.Content.ReadAsStringAsync();

            var registroPost = JsonConvert.DeserializeObject <UserDtoCreateResult>(postResult);

            Assert.Equal(HttpStatusCode.Created, response.StatusCode);
            Assert.Equal(_name, registroPost.Name);
            Assert.Equal(_email, registroPost.Email);
            Assert.True(registroPost.Id != default(Guid));

            //Get All
            response = await client.GetAsync($"{hostApi}users/GetAll");

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            var jsonResult = await response.Content.ReadAsStringAsync();

            var listaFromJson = JsonConvert.DeserializeObject <IEnumerable <UserDto> >(jsonResult);

            Assert.NotNull(listaFromJson);
            Assert.True(listaFromJson.Count() > 0);
            Assert.True(listaFromJson.Where(r => r.Id == registroPost.Id).Count() == 1);

            var updateUserDto = new UserDtoUpdate()
            {
                Id    = registroPost.Id,
                Name  = Faker.Name.FullName(),
                Email = Faker.Internet.Email()
            };

            //PUT
            var stringContent = new StringContent(JsonConvert.SerializeObject(updateUserDto),
                                                  Encoding.UTF8, "application/json");

            response = await client.PutAsync($"{hostApi}users/put", stringContent);

            jsonResult = await response.Content.ReadAsStringAsync();

            var registroAtualizado = JsonConvert.DeserializeObject <UserDtoUpdateResult>(jsonResult);

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.NotEqual(registroPost.Name, registroAtualizado.Name);
            Assert.NotEqual(registroPost.Email, registroAtualizado.Email);

            //GET Id
            response = await client.GetAsync($"{hostApi}users/GetWithId/{registroAtualizado.Id}");

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            jsonResult = await response.Content.ReadAsStringAsync();

            var registroSelecionado = JsonConvert.DeserializeObject <UserDto>(jsonResult);

            Assert.NotNull(registroSelecionado);
            Assert.Equal(registroSelecionado.Name, registroAtualizado.Name);
            Assert.Equal(registroSelecionado.Email, registroAtualizado.Email);

            //DELETE
            response = await client.DeleteAsync($"{hostApi}users/Delete/{registroSelecionado.Id}");

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            //GET ID depois do DELETE
            response = await client.GetAsync($"{hostApi}users/GetWithId/{registroSelecionado.Id}");

            Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
        }
예제 #30
0
        public UsuarioTestes()
        {
            IdUsuario            = Faker.RandomNumber.Next();
            NomeUsuario          = Faker.Name.FullName();
            EmailUsuario         = Faker.Internet.Email();
            RoleUsuario          = "ADM";
            SenhaUsuario         = Faker.Internet.UserName();
            NomeUsuarioAlterado  = Faker.Name.FullName();
            EmailUsuarioAlterado = Faker.Internet.Email();
            RoleUsuarioAlterado  = "Basic";
            SenhaUsuarioAlterado = Faker.Internet.UserName();

            for (int i = 0; i <= 10; i++)
            {
                var dto = new UserDto()
                {
                    Id    = Faker.RandomNumber.Next(),
                    Email = Faker.Internet.Email(),
                    Name  = Faker.Name.FullName(),
                };
                listaUserDto.Add(dto);
            }

            userDto = new UserDto
            {
                Id    = IdUsuario,
                Name  = NomeUsuario,
                Email = EmailUsuario
            };

            userDtoCreate = new UserDtoCreate
            {
                Name  = NomeUsuario,
                Email = EmailUsuario,
                Senha = SenhaUsuario,
                Role  = RoleUsuario
            };

            userDtoCreateReult = new UserDtoCreateReult
            {
                Id    = IdUsuario,
                Name  = NomeUsuario,
                Email = EmailUsuario,
                Senha = SenhaUsuario,
                Role  = RoleUsuario
            };

            userDtoUpdate = new UserDtoUpdate
            {
                Id    = IdUsuario,
                Name  = NomeUsuario,
                Email = EmailUsuario,
                Senha = SenhaUsuario,
                Role  = RoleUsuario
            };

            userDtoUpdateReult = new UserDtoUpdateReult
            {
                Id    = IdUsuario,
                Name  = NomeUsuario,
                Email = EmailUsuario
            };
        }