Exemplo n.º 1
0
        public void WhenThrowsExceptionShouldReturnStatusCode500()
        {
            //Arrange
            var mockLogger = new Mock <ILogger <InsertToDoTaskHandler> >();

            var mock = new Mock <IToDoTaskRepository>();

            mock.Setup(r => r.GetCategoryById(20)).Returns(new Category(20, "Study"));
            mock.Setup(r => r.InsertTasks(It.IsAny <ToDoTask[]>())).Throws(new Exception("Ocorreu um erro inesperado."));

            var controller = new ToDoTaskController(mock.Object, mockLogger.Object);
            var model      = new InsertToDoTask
            {
                CategoryId = 20,
                Title      = "Study XUnit",
                Deadline   = new DateTime(2020, 12, 31)
            };

            //Act
            var result = controller.Post(model);

            //Assert
            Assert.IsType <StatusCodeResult>(result);
            var statusCodeResponse = (result as StatusCodeResult).StatusCode;

            Assert.Equal(500, statusCodeResponse);
        }
        public CommandResult Execute(InsertToDoTask command)
        {
            try
            {
                var task = new ToDoTask
                           (
                    id: 0,
                    title: command.Title,
                    deadline: command.Deadline,
                    category: command.Category,
                    completionDate: null,
                    status: ToDoTaskStatus.Created
                           );

                _logger.LogDebug("Persistindo a tarefa...");
                _repository.InsertTasks(task);

                return(new CommandResult(true));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                return(new CommandResult(false));
            }
        }
Exemplo n.º 3
0
        public void GivenValidToDoTaskShouldReturnOkResult()
        {
            //Arrange
            var mockLogger = new Mock <ILogger <InsertToDoTaskHandler> >();

            var options = new DbContextOptionsBuilder <DbToDoTasksContext>()
                          .UseInMemoryDatabase("DbToDoTaskContext")
                          .Options;
            var context = new DbToDoTasksContext(options);

            context.Categories.Add(new Category(20, "Study"));
            context.SaveChanges();

            var repository = new ToDoTaskRepository(context);

            var controller = new ToDoTaskController(repository, mockLogger.Object);
            var model      = new InsertToDoTask
            {
                CategoryId = 20,
                Title      = "Study XUnit",
                Deadline   = new DateTime(2020, 12, 31)
            };

            //Act
            var result = controller.Post(model);

            //Assert
            Assert.IsType <OkResult>(result);
        }
        public void WhenThrowsExceptionShouldLogMessageException()
        {
            //Arrange
            var errorMessage      = "Ocorreu um erro ao incluir tarefas.";
            var expectedException = new Exception(errorMessage);

            var command = new InsertToDoTask("Study XUnit", new Category("Study"), new DateTime(2020, 12, 31));

            var mockLogger = new Mock <ILogger <InsertToDoTaskHandler> >();

            var mock = new Mock <IToDoTaskRepository>();

            mock.Setup(r => r.InsertTasks(It.IsAny <ToDoTask[]>()))
            .Throws(expectedException);
            var repository = mock.Object;

            var handler = new InsertToDoTaskHandler(repository, mockLogger.Object);

            //Act
            var response = handler.Execute(command);

            //Assert
            mockLogger.Verify(l =>
                              l.Log(
                                  LogLevel.Error,
                                  It.IsAny <EventId>(),
                                  It.IsAny <object>(),
                                  expectedException,
                                  (Func <object, Exception, string>)It.IsAny <object>()
                                  ),
                              Times.Once());
        }
        public void WhenThrowsExceptionResultIsSuccessShouldBeFalse()
        {
            //Arrange
            var command = new InsertToDoTask("Study XUnit", new Category("Study"), new DateTime(2020, 12, 31));

            var mockLogger = new Mock <ILogger <InsertToDoTaskHandler> >();

            var mock = new Mock <IToDoTaskRepository>();

            mock.Setup(r => r.InsertTasks(It.IsAny <ToDoTask[]>()))
            .Throws(new Exception("Ocorreu um erro ao incluir tarefas."));
            var repository = mock.Object;

            var handler = new InsertToDoTaskHandler(repository, mockLogger.Object);

            //Act
            var response = handler.Execute(command);

            //Assert
            Assert.False(response.IsSuccess);
        }
        public void GivenValidToDoTaskShouldIncludeInDatabase()
        {
            //Arrange
            var command = new InsertToDoTask("Study XUnit", new Category("Study"), new DateTime(2020, 12, 31));

            var mock = new Mock <ILogger <InsertToDoTaskHandler> >();

            var options = new DbContextOptionsBuilder <DbToDoTasksContext>()
                          .UseInMemoryDatabase("DbToDoTaskContext")
                          .Options;
            var context    = new DbToDoTasksContext(options);
            var repository = new ToDoTaskRepository(context);

            var handler = new InsertToDoTaskHandler(repository, mock.Object);

            //Act
            handler.Execute(command);

            //Assert
            var task = repository.GetTasks(t => t.Title.Equals(command.Title));
        }
        public IActionResult Post(Models.InsertToDoTask model)
        {
            var categoryCommand = new GetCategoryById(model.CategoryId);
            var category        = new GetCategoryByIdHandler(_repository).Execute(categoryCommand);

            if (category == null)
            {
                return(NotFound("Categoria não encontrada!"));
            }

            var command = new InsertToDoTask(model.Title, category, model.Deadline);
            var handler = new InsertToDoTaskHandler(_repository, _logger);
            var result  = handler.Execute(command);

            if (result.IsSuccess)
            {
                return(Ok());
            }

            return(StatusCode(500));
        }
        public void GivenValidToDoTaskShouldLog()
        {
            //Arrange
            var command = new InsertToDoTask("Study XUnit", new Category("Study"), new DateTime(2020, 12, 31));

            var mockLogger = new Mock <ILogger <InsertToDoTaskHandler> >();

            LogLevel getLogLevel = LogLevel.Error;
            string   getMessage  = string.Empty;

            GetLogMessage getLogMessage = (logLevel, eventId, state, exception, func) =>
            {
                getLogLevel = logLevel;
                getMessage  = func(state, exception);
            };

            mockLogger.Setup(l =>
                             l.Log(
                                 It.IsAny <LogLevel>(),
                                 It.IsAny <EventId>(),
                                 It.IsAny <It.IsAnyType>(),
                                 It.IsAny <Exception>(),
                                 (Func <It.IsAnyType, Exception, string>)It.IsAny <object>()
                                 )).Callback(getLogMessage);

            var mock = new Mock <IToDoTaskRepository>();

            var handler = new InsertToDoTaskHandler(mock.Object, mockLogger.Object);

            //Act
            handler.Execute(command);

            //Assert
            Assert.Equal(LogLevel.Information, getLogLevel);
            Assert.Equal("", getMessage);
        }