public async Task Deve_Atualizar_Registro_Pelo_Servico()
        {
            //Given
            InsertTestViewModel model = new InsertTestViewModel();

            model.Nome    = "Weslley Carneiro";
            model.Contato = "*****@*****.**";

            var services = new ServiceCollection();

            services.AddLogging();
            services.AddAutoMapper(typeof(TestViewModel));
            services.AddContext <TestContext>(new ContextOptionsBuilder());
            services.AddApplicationServices <ITestServiceApplication, TestServiceApplication>("Optsol.Components.Test.Utils");
            services.AddAServices();

            var provider = services.BuildServiceProvider();
            ITestServiceApplication serviceApplication = provider.GetRequiredService <ITestServiceApplication>();
            IApiControllerBase <TestEntity, TestViewModel, TestViewModel, InsertTestViewModel, UpdateTestViewModel> controllerBase =
                new ApiControllerBase <TestEntity, TestViewModel, TestViewModel, InsertTestViewModel, UpdateTestViewModel>(
                    provider.GetRequiredService <ILogger <ApiControllerBase <TestEntity, TestViewModel, TestViewModel, InsertTestViewModel, UpdateTestViewModel> > >(),
                    provider.GetRequiredService <IBaseServiceApplication <TestEntity, TestViewModel, TestViewModel, InsertTestViewModel, UpdateTestViewModel> >(),
                    provider.GetRequiredService <IResponseFactory>());

            await serviceApplication.InsertAsync(model);

            var data        = (await serviceApplication.GetAllAsync()).DataList.Single();
            var updateModel = new UpdateTestViewModel();

            updateModel.Id      = data.Id;
            updateModel.Nome    = $"Weslley Alterado";
            updateModel.Contato = model.Contato;

            //When
            var actionResult = await controllerBase.UpdateAsync(updateModel);

            //Then
            ((OkObjectResult)actionResult).StatusCode.Should().NotBeNull();
            ((OkObjectResult)actionResult).StatusCode.Should().Be((int)HttpStatusCode.OK);

            var resultObj = JsonConvert.DeserializeObject <Response>(((OkObjectResult)actionResult).Value.ToJson());

            resultObj.Should().NotBeNull();
            resultObj.Success.Should().BeTrue();
            resultObj.Failure.Should().BeFalse();
            resultObj.Messages.Should().BeEmpty();

            var resultService = await serviceApplication.GetByIdAsync(updateModel.Id);

            resultService.Data.Should().NotBeNull();
            resultService.Data.Id.Should().NotBeEmpty();
            resultService.Data.Nome.Should().Be(updateModel.Nome);
            resultService.Data.Contato.Should().Be(updateModel.Contato);
            resultService.Data.Ativo.Should().Be("Inativo");
        }
Ejemplo n.º 2
0
        public async Task Deve_Atualizar_Registro_Pelo_Servico()
        {
            //Given
            InsertTestViewModel model = new InsertTestViewModel();

            model.Nome    = "Weslley Carneiro";
            model.Contato = "*****@*****.**";

            var services = new ServiceCollection();

            services.AddLogging();
            services.AddAutoMapper(typeof(TestViewModel));
            services.AddContext <TestContext>(new ContextOptionsBuilder());
            services.AddApplicationServices <ITestServiceApplication, TestServiceApplication>("Optsol.Components.Test.Utils");

            var provider = services.BuildServiceProvider();
            ITestServiceApplication serviceApplication = provider.GetRequiredService <ITestServiceApplication>();

            await serviceApplication.InsertAsync(model);

            var data        = (await serviceApplication.GetAllAsync()).DataList.Single();
            var updateModel = new UpdateTestViewModel();

            updateModel.Id      = data.Id;
            updateModel.Nome    = $"Weslley Alterado";
            updateModel.Contato = model.Contato;

            //When
            var modelResult = await serviceApplication.UpdateAsync(updateModel);

            //Then
            var entity = await serviceApplication.GetAllAsync();

            modelResult.Invalid.Should().BeFalse();
            modelResult.Notifications.Should().HaveCount(0);

            entity.DataList.Should().HaveCount(1);
            entity.DataList.Single().Id.Should().NotBeEmpty();
            entity.DataList.Single().Nome.Should().Be(updateModel.Nome);
            entity.DataList.Single().Contato.Should().Be(updateModel.Contato);
            entity.DataList.Single().Ativo.Should().Be("Inativo");
        }
        public async Task Deve_Atualizar_Registro_Pelo_Servico()
        {
            //Given
            var entity = default(TestEntity);

            var provider = GetProviderConfiguredServicesFromContext()
                           .CreateTestEntitySeedInContext(afterInsert: (testEntityList) =>
            {
                entity = testEntityList.First();
            });

            var notificationContext = provider.GetRequiredService <NotificationContext>();
            var serviceApplication  = provider.GetRequiredService <ITestServiceApplication>();

            var updateModel = new UpdateTestViewModel();

            updateModel.Id      = entity.Id;
            updateModel.Nome    = $"{entity.Nome.Nome} Alterado";
            updateModel.Contato = entity.Email.ToString();

            //When
            Action action = () => serviceApplication.UpdateAsync <UpdateTestViewModel, UpdateTestViewModel>(updateModel);

            //Then
            action.Should().NotThrow();

            notificationContext.HasNotifications.Should().BeFalse();
            notificationContext.Notifications.Should().HaveCount(0);

            var viewModelResult = await serviceApplication.GetByIdAsync <TestViewModel>(updateModel.Id);

            viewModelResult.Should().NotBeNull();

            viewModelResult.IsValid.Should().BeTrue();
            viewModelResult.Notifications.Should().BeEmpty();

            viewModelResult.Id.Should().Be(updateModel.Id);
            viewModelResult.Nome.Should().Be(updateModel.Nome);
            viewModelResult.Contato.Should().Be(updateModel.Contato);
        }
        public void Nao_Deve_Atualizar_Registro_Pelo_Servico(UpdateTestViewModel viewModel, string[] expectedErrorProperty, int expectedErrosCount)
        {
            //Given
            var provider = GetProviderConfiguredServicesFromContext()
                           .CreateTestEntitySeedInContext(afterInsert: (testEntityList) =>
            {
                viewModel.Id = testEntityList.First().Id;
            });

            var notificationContext = provider.GetRequiredService <NotificationContext>();
            var serviceApplication  = provider.GetRequiredService <ITestServiceApplication>();

            //When
            Action action = () => serviceApplication.UpdateAsync <UpdateTestViewModel, UpdateTestViewModel>(viewModel);

            //Then
            action.Should().NotThrow();

            notificationContext.HasNotifications.Should().BeTrue();
            notificationContext.Notifications.Should().HaveCount(expectedErrosCount);
            notificationContext.Notifications.Any(a => expectedErrorProperty.Contains(a.Key)).Should().BeTrue();
        }
        public void Deve_Registrar_Logs_No_Servico()
        {
            //Given
            var entity = new TestEntity();

            entity.Validate();

            var entity2 = new TestEntity();

            entity2.Validate();

            var model = new TestViewModel();

            model.Nome    = "Weslley Carneiro";
            model.Contato = "*****@*****.**";

            var insertModel = new InsertTestViewModel();

            insertModel.Nome    = "Weslley Carneiro";
            insertModel.Contato = "*****@*****.**";

            var updateModel = new UpdateTestViewModel();

            updateModel.Id      = Guid.NewGuid();
            updateModel.Nome    = "Weslley Carneiro";
            updateModel.Contato = "*****@*****.**";

            Mock <IMapper> mapperMock = new Mock <IMapper>();

            mapperMock.Setup(mapper => mapper.Map <TestViewModel>(It.IsAny <TestEntity>())).Returns(model);
            mapperMock.Setup(mapper => mapper.Map <TestEntity>(It.IsAny <TestViewModel>())).Returns(entity);
            mapperMock.Setup(mapper => mapper.Map <TestEntity>(It.IsAny <InsertTestViewModel>())).Returns(entity);
            mapperMock.Setup(mapper => mapper.Map <TestEntity>(It.IsAny <UpdateTestViewModel>())).Returns(entity);

            Mock <IUnitOfWork> unitOfWork = new Mock <IUnitOfWork>();

            unitOfWork.Setup(uow => uow.CommitAsync()).ReturnsAsync(true);

            Mock <IServiceResultFactory> serviceResultFactoryMock = new Mock <IServiceResultFactory>();

            serviceResultFactoryMock.Setup(factory => factory.Create()).Returns(new ServiceResult());
            serviceResultFactoryMock.Setup(factory => factory.Create <TestViewModel>(It.IsAny <TestViewModel>())).Returns(new ServiceResult <TestViewModel>(model));

            Mock <IReadRepository <TestEntity, Guid> > readRepository = new Mock <IReadRepository <TestEntity, Guid> >();

            readRepository.Setup(repository => repository.GetByIdAsync(It.IsAny <Guid>())).ReturnsAsync(entity);
            readRepository.Setup(repository => repository.GetAllAsync()).Returns(GetAllAggregateRootAsyncEnumerable(entity, entity2));

            Mock <IWriteRepository <TestEntity, Guid> > writeRepository = new Mock <IWriteRepository <TestEntity, Guid> >();

            var logger  = new XunitLogger <BaseServiceApplication <TestEntity, TestViewModel, TestViewModel, InsertTestViewModel, UpdateTestViewModel> >();
            var service = new BaseServiceApplication <TestEntity, TestViewModel, TestViewModel, InsertTestViewModel, UpdateTestViewModel>(
                mapperMock.Object,
                logger,
                serviceResultFactoryMock.Object,
                unitOfWork.Object,
                readRepository.Object,
                writeRepository.Object);

            //When
            service.GetByIdAsync(entity.Id).ConfigureAwait(false);
            service.GetAllAsync().ConfigureAwait(false);
            service.InsertAsync(insertModel).ConfigureAwait(false);
            service.UpdateAsync(updateModel).ConfigureAwait(false);
            service.DeleteAsync(entity.Id).ConfigureAwait(false);

            //Then
            var msgConstructor       = $"Inicializando Application Service<{ entity.GetType().Name }, Guid>";
            var msgGetByIdAsync      = $"Método: GetByIdAsync({{ id:{ entity.Id } }}) Retorno: type TestViewModel";
            var msgGetAllAsync       = $"Método: GetAllAsync() Retorno: IEnumerable<{ model.GetType().Name }>";
            var msgInsertAsync       = $"Método: InsertAsync({{ viewModel:{ insertModel.ToJson() } }})";
            var msgInsertAsyncMapper = $"Método: InsertAsync Mapper: { insertModel.GetType().Name } To: { entity.GetType().Name }";
            var msgUpdateAsync       = $"Método: UpdateAsync({{ viewModel:{ updateModel.ToJson() } }})";
            var msgUpdateAsyncMapper = $"Método: UpdateAsync Mapper: { updateModel.GetType().Name } To: { entity.GetType().Name }";
            var msgDeleteAsync       = $"Método: DeleteAsync({{ id:{ entity.Id } }})";

            logger.Logs.Should().HaveCount(10);
            logger.Logs.Any(a => a.Equals(msgConstructor)).Should().BeTrue();
            logger.Logs.Any(a => a.Equals(msgGetByIdAsync)).Should().BeTrue();
            logger.Logs.Any(a => a.Equals(msgGetAllAsync)).Should().BeTrue();
            logger.Logs.Any(a => a.Equals(msgInsertAsync)).Should().BeTrue();
            logger.Logs.Any(a => a.Contains(msgInsertAsyncMapper)).Should().BeTrue();
            logger.Logs.Any(a => a.Equals(msgUpdateAsync)).Should().BeTrue();
            logger.Logs.Any(a => a.Contains(msgUpdateAsyncMapper)).Should().BeTrue();
            logger.Logs.Any(a => a.Equals(msgDeleteAsync)).Should().BeTrue();
        }
Ejemplo n.º 6
0
        public async Task Deve_Registrar_Logs_No_ApiController()
        {
            //Given
            var model           = new TestViewModel();
            var insertViewModel = new InsertTestViewModel();
            var updateViewModel = new UpdateTestViewModel();

            var testSearchDto = new TestSearchDto();

            testSearchDto.Nome      = "Nome";
            testSearchDto.SobreNome = "Sobrenome";
            var searchDto = new SearchRequest <TestSearchDto>();

            searchDto.Search = testSearchDto;

            var entity = new TestEntity(
                new NomeValueObject("Weslley", "Carneiro"),
                new EmailValueObject("*****@*****.**"));

            model.Id = entity.Id;

            var logger = new XunitLogger <
                ApiControllerBase <TestEntity
                                   , TestViewModel
                                   , TestViewModel
                                   , InsertTestViewModel
                                   , UpdateTestViewModel
                                   , TestSearchDto> >();
            var loggerFactoryMock = new Mock <ILoggerFactory>();

            loggerFactoryMock.Setup(setup => setup.CreateLogger(It.IsAny <string>())).Returns(logger);

            Mock <IMapper> mapperMock = new Mock <IMapper>();

            mapperMock.Setup(mapper => mapper.Map <TestViewModel>(It.IsAny <TestEntity>())).Returns(model);
            mapperMock.Setup(mapper => mapper.Map <TestEntity>(It.IsAny <TestViewModel>())).Returns(entity);

            var mockApplicationService = new Mock <ITestServiceApplication>();

            mockApplicationService.Setup(setup => setup.InsertAsync <InsertTestViewModel, InsertTestViewModel>(It.IsAny <InsertTestViewModel>())).ReturnsAsync(insertViewModel);
            mockApplicationService.Setup(setup => setup.UpdateAsync <UpdateTestViewModel, UpdateTestViewModel>(It.IsAny <UpdateTestViewModel>())).ReturnsAsync(updateViewModel);

            var mockResponseFactory = new Mock <IResponseFactory>();

            mockResponseFactory.Setup(setup => setup.Create()).Returns(new Response());
            mockResponseFactory.Setup(setup => setup.Create(It.IsAny <TestViewModel>())).Returns(new Response <TestViewModel>(model, true));
            mockResponseFactory.Setup(setup => setup.Create(It.IsAny <IEnumerable <TestViewModel> >())).Returns(new ResponseList <TestViewModel>(new[] { model }, true));
            mockResponseFactory.Setup(setup => setup.Create(It.IsAny <SearchResult <TestViewModel> >())).Returns(new ResponseSearch <TestViewModel>(new SearchResult <TestViewModel>(1, 10)
            {
                Items = new[] { model }
            }, true));
            mockResponseFactory.Setup(setup => setup.Create(It.IsAny <InsertTestViewModel>())).Returns(new Response <InsertTestViewModel>(insertViewModel, true));
            mockResponseFactory.Setup(setup => setup.Create(It.IsAny <UpdateTestViewModel>())).Returns(new Response <UpdateTestViewModel>(updateViewModel, true));


            var controller = new TestController(loggerFactoryMock.Object, mockApplicationService.Object, mockResponseFactory.Object);

            //When
            await controller.GetAllAsync();

            await controller.GetAllAsync(searchDto);

            await controller.GetByIdAsync(model.Id);

            await controller.InsertAsync(insertViewModel);

            await controller.UpdateAsync(updateViewModel);

            await controller.DeleteAsync(model.Id);

            //Then
            var msgContructor           = "Inicializando Controller Base<TestEntity, Guid>";
            var msgGetById              = $"Método: GetByIdAsync({{ id:{ entity.Id } }})";
            var msgGetAllAsync          = "Método: GetAllAsync() Retorno: IActionResult";
            var msgGetAllPaginatedAsync = $"Método: GetAllAsync({ searchDto.ToJson() }) Retorno: IActionResult";
            var msgInsertAsync          = $"Método: InsertAsync({{ viewModel:{ insertViewModel.ToJson() } }})";
            var msgUpdateAsync          = $"Método: UpdateAsync({{ viewModel:{ updateViewModel.ToJson() } }})";
            var msgDeleteAsync          = $"Método: DeleteAsync({{ id:{ entity.Id } }})";

            logger.Logs.Should().HaveCount(7);
            logger.Logs.Any(a => a.Equals(msgGetById)).Should().BeTrue();
            logger.Logs.Any(a => a.Equals(msgContructor)).Should().BeTrue();
            logger.Logs.Any(a => a.Equals(msgGetAllAsync)).Should().BeTrue();
            logger.Logs.Any(a => a.Equals(msgGetAllPaginatedAsync)).Should().BeTrue();
            logger.Logs.Any(a => a.Equals(msgInsertAsync)).Should().BeTrue();
            logger.Logs.Any(a => a.Equals(msgUpdateAsync)).Should().BeTrue();
            logger.Logs.Any(a => a.Equals(msgDeleteAsync)).Should().BeTrue();
        }
Ejemplo n.º 7
0
        public ActionResult UpdateTest([DataSourceRequest] DataSourceRequest request, UpdateTestViewModel model)
        {
            if (model != null && ModelState.IsValid)
            {
                using (var repository = GetRepository())
                {
                    var result = ValidateTaxonomyFields(model);

                    if (result.ValidationMessages.Count > 0)
                    {
                        return(new JsonHttpStatusResult(new { Message = result.ValidationMessages }, HttpStatusCode.InternalServerError));
                    }
                    if (model.Id != model.OldId)
                    {
                        if (!IsUniqueId(model.Id))
                        {
                            model.Id = model.OldId;
                            return(new JsonHttpStatusResult(new { Message = UserMessages.FIELD_ID }, HttpStatusCode.InternalServerError));
                        }
                    }


                    var entity = new TestModel()
                    {
                        Description = model.Description,
                        Id          = model.Id
                    };

                    try
                    {
                        repository.TestRepository.Update(model.OldId, entity);
                    }
                    catch (Exception e)
                    {
                        GetLogger().LogException(e, string.Format("UpdateTest({0})", model.Id));

                        return(new JsonHttpStatusResult(new { Message = UserMessages.UNKNOWN_ERROR }, HttpStatusCode.InternalServerError));
                    }

                    repository.Commit();
                }
            }
            return(Json(new[] { model }.ToDataSourceResult(request, ModelState)));
        }
Ejemplo n.º 8
0
        public async Task Deve_Registrar_Logs_No_Servico()
        {
            //Given
            var entity = new TestEntity();

            entity.Validate();

            var entity2 = new TestEntity();

            entity2.Validate();

            var model = new TestViewModel();

            model.Nome    = "Weslley Carneiro";
            model.Contato = "*****@*****.**";

            var insertModel = new InsertTestViewModel();

            insertModel.Nome    = "Weslley Carneiro";
            insertModel.Contato = "*****@*****.**";

            var updateModel = new UpdateTestViewModel();

            updateModel.Id      = Guid.NewGuid();
            updateModel.Nome    = "Weslley Carneiro";
            updateModel.Contato = "*****@*****.**";

            var mapperMock = new Mock <IMapper>();

            mapperMock.Setup(mapper => mapper.Map <TestViewModel>(It.IsAny <TestEntity>())).Returns(model);
            mapperMock.Setup(mapper => mapper.Map <TestEntity>(It.IsAny <TestViewModel>())).Returns(entity);
            mapperMock.Setup(mapper => mapper.Map <TestEntity>(It.IsAny <InsertTestViewModel>())).Returns(entity);
            mapperMock.Setup(mapper => mapper.Map <TestEntity>(It.IsAny <UpdateTestViewModel>())).Returns(entity);

            var unitOfWork = new Mock <IUnitOfWork>();

            unitOfWork.Setup(uow => uow.CommitAsync()).ReturnsAsync(1);

            var readRepository = new Mock <IReadRepository <TestEntity, Guid> >();

            readRepository.Setup(repository => repository.GetByIdAsync(It.IsAny <Guid>())).ReturnsAsync(entity);
            readRepository.Setup(repository => repository.GetAllAsync()).ReturnsAsync(new List <TestEntity> {
                entity, entity2
            });

            var writeRepository = new Mock <IWriteRepository <TestEntity, Guid> >();

            var notificationContextMock = new Mock <NotificationContext>();

            var logger            = new XunitLogger <BaseServiceApplication <TestEntity> >();
            var loggerFactoryMock = new Mock <ILoggerFactory>();

            loggerFactoryMock.Setup(setup => setup.CreateLogger(It.IsAny <string>())).Returns(logger);

            var service = new BaseServiceApplication <TestEntity>(
                mapperMock.Object,
                loggerFactoryMock.Object,
                unitOfWork.Object,
                readRepository.Object,
                writeRepository.Object,
                notificationContextMock.Object);

            //When
            await service.GetAllAsync <TestViewModel>();

            await service.GetByIdAsync <TestViewModel>(entity.Id);

            await service.InsertAsync <InsertTestViewModel, InsertTestViewModel>(insertModel);

            await service.UpdateAsync <UpdateTestViewModel, UpdateTestViewModel>(updateModel);

            await service.DeleteAsync(entity.Id);

            //Then
            var msgConstructor       = $"Inicializando Application Service<{ entity.GetType().Name }, Guid>";
            var msgGetByIdAsync      = $"Método: GetByIdAsync({{ id:{ entity.Id } }}) Retorno: type TestViewModel";
            var msgGetAllAsync       = $"Método: GetAllAsync() Retorno: IEnumerable<{ model.GetType().Name }>";
            var msgInsertAsync       = $"Método: InsertAsync({{ viewModel:{ insertModel.ToJson() } }})";
            var msgInsertAsyncMapper = $"Método: InsertAsync Mapper: { insertModel.GetType().Name } To: { entity.GetType().Name }";
            var msgUpdateAsync       = $"Método: UpdateAsync({{ viewModel:{ updateModel.ToJson() } }})";
            var msgUpdateAsyncMapper = $"Método: UpdateAsync Mapper: { updateModel.GetType().Name } To: { entity.GetType().Name }";
            var msgDeleteAsync       = $"Método: DeleteAsync({{ id:{ entity.Id } }})";

            logger.Logs.Should().HaveCount(11);
            logger.Logs.Any(a => a.Equals(msgConstructor)).Should().BeTrue();
            logger.Logs.Any(a => a.Equals(msgGetByIdAsync)).Should().BeTrue();
            logger.Logs.Any(a => a.Equals(msgGetAllAsync)).Should().BeTrue();
            logger.Logs.Any(a => a.Equals(msgInsertAsync)).Should().BeTrue();
            logger.Logs.Any(a => a.Contains(msgInsertAsyncMapper)).Should().BeTrue();
            logger.Logs.Any(a => a.Equals(msgUpdateAsync)).Should().BeTrue();
            logger.Logs.Any(a => a.Contains(msgUpdateAsyncMapper)).Should().BeTrue();
            logger.Logs.Any(a => a.Equals(msgDeleteAsync)).Should().BeTrue();
        }