Example #1
0
        public async Task Test()
        {
            var todo = new TodoDto
            {
                Title       = "Title",
                Description = "Description",
                Completed   = true
            };

            var mapperConfiguration = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new AutoMapperProfileConfiguration());
            });
            var mapper      = mapperConfiguration.CreateMapper();
            var mockOptions = new Mock <DbContextOptions <ApplicationContext> >();

            mockOptions.Setup(m => m.ContextType).Returns(typeof(ApplicationContext));
            var mockDbSet   = new Mock <DbSet <Todo> >();
            var mockContext = new Mock <ApplicationContext>(mockOptions.Object);

            mockContext.Setup(m => m.Todos).Returns(mockDbSet.Object);
            mockContext.Setup(m => m.SaveChangesAsync(default(CancellationToken))).Returns(() => Task.Run(() => 1)).Verifiable();

            var service     = new TodoService(mockContext.Object, mapper);
            var createdTodo = await service.Create(todo);

            mockDbSet.Verify(m => m.Add(It.IsAny <Todo>()), Times.Once());
            mockContext.Verify(m => m.SaveChangesAsync(default(CancellationToken)), Times.Once());
        }
Example #2
0
        public async Task GivenAValidTodoDto_WhenCreate_ThenANewTodoIsCreated()
        {
            var options = CreateNewContextOptions();
            var mapper  = CreateMapper();

            var todo = new TodoDto
            {
                Title       = "Title",
                Description = "Description",
                Completed   = true
            };

            using (var context = new ApplicationContext(options))
            {
                var service = new TodoService(context, mapper);

                var createdTodo = await service.Create(todo);

                Assert.True(createdTodo.Id > 0);
                Assert.Equal(todo.Title, createdTodo.Title);
                Assert.Equal(todo.Description, createdTodo.Description);
                Assert.Equal(todo.Completed, createdTodo.Completed);
            }

            using (var context = new ApplicationContext(options))
            {
                Assert.Equal(1, context.Todos.Count());
                var createdTodo = context.Todos.First();
                Assert.True(createdTodo.Id > 0);
                Assert.Equal(todo.Title, createdTodo.Title);
                Assert.Equal(todo.Description, createdTodo.Description);
                Assert.Equal(todo.Completed, createdTodo.Completed);
            }
        }
 public ActionResult <Todo> AddTodo(string task)
 {
     return(_todoService.Create(new Todo()
     {
         Task = task
     }));
 }
        public ActionResult <TodoReadDto> Create(TodoCreateDto dto)
        {
            int userId = Convert.ToInt32(HttpContext.Items["id"]);

            TodoReadDto result = _service.Create(userId, dto);

            return(Ok(result));
        }
Example #5
0
        public FubuContinuation post_create(Create todo)
        {
            var todoToCreate = new Domain.Todo(todo.Name, todo.IsComplete);

            _toDoService.Create(todoToCreate);

            return(FubuContinuation.RedirectTo <TodoEndpoint>(endpoint => endpoint.get_list()));
        }
Example #6
0
        public async void CanGetTodoById()
        {
            using (var context = CreateContext())
            {
                var todoService = new TodoService(context);
                var user        = new User()
                {
                    Email = "*****@*****.**", PasswordHash = "!@#QWE"
                };
                var todo1 = await todoService.Create("Test", "Test", user);

                var todo2 = await todoService.Create("Test1", "Test1", user);

                var getTodo = await todoService.GetById(todo2.Id);

                Assert.Equal(getTodo, todo2);
            }
        }
        public async Task Create_Returns_ViewModel()
        {
            using (var context = new TasksContext(_options))
            {
                var service       = new TodoService(context);
                var todoViewModel = await service.Create("sample descr");

                Assert.AreEqual("sample descr", todoViewModel.Description);
            }
        }
        public async Task Create_Adds_ID_To_Entity()
        {
            using (var context = new TasksContext(_options))
            {
                var service       = new TodoService(context);
                var todoViewModel = await service.Create("sample descr");

                Assert.IsNotNull(todoViewModel.ID);
            }
        }
Example #9
0
        public async void CanGetAllTodosByUserId()
        {
            using (var context = CreateContext())
            {
                var todoService = new TodoService(context);
                var user        = new User()
                {
                    Email = "*****@*****.**", PasswordHash = "!@#QWE"
                };

                await todoService.Create("Test", "Test", user);

                await todoService.Create("Test1", "Test1", user);

                var todos = todoService.GetAll(user.Id);

                Assert.Equal(2, todos.Count);
            }
        }
Example #10
0
        public ActionResult <Todo> Create(Todo todo)
        {
            if (todo.DateCreated == null)
            {
                todo.DateCreated = DateTime.Now;
            }

            _todoService.Create(todo);

            return(CreatedAtRoute("GetTodo", new { id = todo.Id.ToString() }, todo));
        }
Example #11
0
 public async Task <ActionResult <object> > Create([FromBody] TodoForm form)
 {
     try
     {
         return(await _todoService.Create(form));
     }
     catch (Exception ex)
     {
         return(new ApiResponse(ex.Message));
     }
 }
Example #12
0
        public void Should_Create_A_Todo_WithoutDefaultId()
        {
            var todoStub = TodoModelStub.GetSimpleTodo();

            _repositoryMock.Setup(p => p.Add(todoStub)).Returns(todoStub);

            var todoService = new TodoService(_repositoryMock.Object);

            var(validation, result) = todoService.Create(todoStub);

            Assert.AreEqual(null, validation);
        }
        public void Create_addsItemAndReturnsWithId()
        {
            subject = new TodoService(mockContext.Object, logger);
            TodoItem todoItem = new TodoItem {
                Name = "New", IsComplete = false
            };
            TodoItem saved = subject.Create(todoItem);

            mockContext.Verify(s => s.Add(todoItem));

            Assert.Equal(todoItem, saved);
        }
Example #14
0
        public void TodoService_Should_Sort()
        {
            var userId = Guid.NewGuid();

            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
                          .Options;

            var mockMapper = new MapperConfiguration(cfg => { cfg.AddProfile(new MappingDTOProfile()); });
            var mapper     = mockMapper.CreateMapper();

            using (var context = new ApplicationDbContext(options))
            {
                var service = new TodoService(context, mapper);

                Assert.Equal(0, context.Todos.Count());
                for (var i = 0; i < 50; i++)
                {
                    var ret1 = service.Create(new CreateTODO()
                    {
                        PublicId = Guid.NewGuid(), UserId = userId,
                        Created  = new DateTime(2000, 1, 1).AddDays(i)
                    });
                }

                Assert.Equal(50, context.Todos.Count());

                var list1 = service.List(new ListTODO()
                {
                    Page = 1, PageSize = 10, UserId = userId, OrderBy = nameof(TodoEntity.PublicId), Asc = true
                });
                var list2 = service.List(new ListTODO()
                {
                    Page = 1, PageSize = 10, UserId = userId, OrderBy = nameof(TodoEntity.PublicId), Asc = false
                });
                var list3 = service.List(new ListTODO()
                {
                    Page = 1, PageSize = 10, UserId = userId, OrderBy = nameof(TodoEntity.Created), Asc = true
                });
                var list4 = service.List(new ListTODO()
                {
                    Page = 1, PageSize = 10, UserId = userId, OrderBy = nameof(TodoEntity.Created), Asc = false
                });

                var first1 = list1.Items.First().PublicId;
                var first2 = list2.Items.First().PublicId;
                var first3 = list3.Items.First().PublicId;
                var first4 = list4.Items.First().PublicId;

                Assert.Equal(4, new[] { first1, first2, first3, first4 }.Distinct().Count());
            }
        }
Example #15
0
        public IActionResult Create(CreateVM task) // Model binding
        {
            // Validate (server-side)
            if (!ModelState.IsValid)
            {
                return(View(task));
            }

            // Add customer to DB
            service.Create(task);

            // Redirect to index
            return(RedirectToAction("Create"));
        }
Example #16
0
        public void Should_Refuse_To_Create_A_Todo_InvalidDate()
        {
            var todoStub = TodoModelStub.GetSimpleTodo();

            todoStub.Expires = todoStub.Expires.AddDays(-2);

            _repositoryMock.Setup(p => p.Add(todoStub)).Returns(todoStub);

            var todoService = new TodoService(_repositoryMock.Object);

            var(validation, result) = todoService.Create(todoStub);

            Assert.IsFalse(validation == null);
            Assert.IsTrue(validation.Errors.Count > 0);
        }
        public async Task Create_Adds_Entity_To_Db()
        {
            int initialCount;

            using (var context = new TasksContext(_options))
            {
                initialCount = context.Todos.Count();

                var service = new TodoService(context);
                await service.Create("sample descr");
            }

            using (var context = new TasksContext(_options))
            {
                Assert.AreEqual(initialCount + 1, context.Todos.Count());
            }
        }
Example #18
0
        public void SearchTodo()
        {
            var options = new DbContextOptionsBuilder <TodoContext>()
                          .UseInMemoryDatabase(databaseName: "Add_writes_to_database")
                          .Options;

            using (var context = new TodoContext(options))
            {
                var      service = new TodoService(context);
                TodoItem item    = new TodoItem();
                item.Name       = "go to store";
                item.Id         = 1;
                item.IsComplete = false;
                service.Create(item);
                Assert.Equal(service.GetById(1), item);
            }
        }
Example #19
0
        public IActionResult PostTodoItem(TodoItem item)
        {
            try
            {
                if (item.Name == null)
                {
                    return(BadRequest("The parameter name is required."));
                }

                _service.Create(item);
                return(Ok("Item has been created successfully."));
            }
            catch (Exception)
            {
                return(StatusCode(500));
            }
        }
Example #20
0
        public async void CanCreateTodo()
        {
            using (var context = CreateContext())
            {
                var todoService = new TodoService(context);
                var user        = new User()
                {
                    Email = "*****@*****.**", PasswordHash = "!@#QWE"
                };
                var todoItem = await todoService.Create("Test", "Test", user);

                Assert.NotNull(todoItem);
                Assert.True(todoItem.Id > 0);

                await todoService.Delete(todoItem.Id);
            }
        }
Example #21
0
        public void DeleteTodo()
        {
            var options = new DbContextOptionsBuilder <TodoContext>()
                          .UseInMemoryDatabase(databaseName: "Add_writes_to_database")
                          .Options;

            using (var context = new TodoContext(options))
            {
                var      service = new TodoService(context);
                TodoItem item    = new TodoItem();
                item.Name       = "Go to store";
                item.Id         = 1;
                item.IsComplete = false;
                service.Create(item);
                service.Delete(1);
                Assert.Equal(0, context.TodoItems.ToList().Count);
            }
        }
Example #22
0
        public void UpdateTodo()
        {
            var options = new DbContextOptionsBuilder <TodoContext>()
                          .UseInMemoryDatabase(databaseName: "Add_writes_to_database")
                          .Options;

            using (var context = new TodoContext(options))
            {
                var      service = new TodoService(context);
                TodoItem item    = new TodoItem();
                item.Name       = "go to store";
                item.Id         = 1;
                item.IsComplete = false;
                service.Create(item);
                TodoItem newItem = new TodoItem();
                newItem.Name = "go to movies";
                Assert.NotEqual(item, service.Update(1, newItem));
            }
        }
Example #23
0
        public async void CreateAddsNewTodo()
        {
            mockTodoRepository
            .Setup(r => r.Add(It.IsAny <Todo>()))
            .Returns((Todo newItem) =>
            {
                todoItems.Add(newItem);
                return(Task.CompletedTask);
            });
            mockTodoRepository.VerifyNoOtherCalls();

            var serviceToTest = new TodoService(mockTodoRepository.Object);
            var newTodo       = new Todo {
                Title = "Check"
            };

            await serviceToTest.Create(newTodo);

            Assert.Contains(todoItems, t => t.Title == newTodo.Title);
        }
Example #24
0
        public async void CanUpdateExistingTodo()
        {
            using (var context = CreateContext())
            {
                var todoService = new TodoService(context);
                var user        = new User()
                {
                    Email = "*****@*****.**", PasswordHash = "!@#QWE"
                };
                var todo = await todoService.Create("Test", "Test", user);

                todo.Title      = "Test Updated";
                todo.IsComplete = true;

                var result = await todoService.Update(todo);

                var updated = await todoService.GetById(todo.Id);

                Assert.Equal(1, result);
                Assert.Equal("Test Updated", updated.Title);
                Assert.True(updated.IsComplete);
            }
        }
Example #25
0
 public IActionResult Post([FromBody] Todo todo)
 {
     return(CreatedAtAction("Get", new { id = todo.Id }, todoService.Create(todo)));
 }
Example #26
0
        public void TodoService_Should_CRUD()
        {
            var userId = Guid.NewGuid();

            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
                          .Options;

            var mockMapper = new MapperConfiguration(cfg => { cfg.AddProfile(new MappingDTOProfile()); });
            var mapper     = mockMapper.CreateMapper();

            using (var context = new ApplicationDbContext(options))
            {
                var service = new TodoService(context, mapper);


                Assert.Equal(0, context.Todos.Count());
                var list1 = service.List(new ListTODO()
                {
                    Page = 1, PageSize = 10, UserId = userId
                });
                Assert.Equal(0, list1.TotalItems);
                Assert.Equal(0, list1.Items.Count());

                for (var i = 0; i < 50; i++)
                {
                    var ret1 = service.Create(new CreateTODO()
                    {
                        Title = "item " + i, PublicId = Guid.NewGuid(), UserId = userId
                    });
                    Assert.Equal(false, ret1.HasError);
                }

                Assert.Equal(50, context.Todos.Count());

                var list2 = service.List(new ListTODO()
                {
                    Page = 1, PageSize = 10, UserId = userId
                });
                Assert.Equal(50, list2.TotalItems);
                Assert.Equal(10, list2.Items.Count());

                var editId = context.Todos.Skip(3).First().PublicId;

                var edit1 = service.Find(new FindToDoRequest()
                {
                    PublicId = editId, UserId = userId
                });
                Assert.Equal(false, edit1.HasError);
                Assert.NotNull(edit1.Data);
                var origField = edit1.Data.Title;

                const string newValue = "new value";
                service.Update(new UpdateTODO()
                {
                    Title = newValue, PublicId = editId, UserId = userId
                });

                var edit2 = service.Find(new FindToDoRequest()
                {
                    PublicId = editId, UserId = userId
                });
                Assert.Equal(false, edit1.HasError);
                Assert.NotNull(edit1.Data);
                Assert.Equal(newValue, edit1.Data.Title);
                Assert.Equal(newValue, edit1.Data.Title);
                Assert.Equal(editId, edit1.Data.PublicId);

                service.Delete(new DeleteTODO()
                {
                    PublicId = editId, UserId = userId
                });
                Assert.Equal(50, context.Todos.Count());
                var list3 = service.List(new ListTODO()
                {
                    Page = 1, PageSize = 10, UserId = userId
                });
                Assert.Equal(49, list3.TotalItems);

                var newId = Guid.NewGuid();
                var cr1   = service.Create(new CreateTODO()
                {
                    Title = newValue, PublicId = newId, UserId = userId
                });
                Assert.Equal(false, cr1.HasError);
                Assert.NotNull(cr1.Data);
                Assert.Equal(newValue, cr1.Data.Title);
                Assert.Equal(newId, cr1.Data.PublicId);

                Assert.Equal(51, context.Todos.Count());
                var list4 = service.List(new ListTODO()
                {
                    Page = 1, PageSize = 10, UserId = userId
                });
                Assert.Equal(50, list4.TotalItems);
            }

            // Use a separate instance of the context to verify correct data was saved to database
            using (var context = new ApplicationDbContext(options))
            {
                Assert.Equal(50, context.Todos.Count(x => !x.IsDeleted));
                Assert.Equal(51, context.Todos.Count());
            }
        }
Example #27
0
 public ActionResult <Todo> Post(Todo todo)
 {
     return(_todoService.Create(todo));
 }
Example #28
0
        public ActionResult Create(string content)
        {
            service.Create(content);

            return(RedirectToAction("Index"));
        }
Example #29
0
        public ActionResult <Todo> Create(Todo todo)
        {
            _todoService.Create(todo);

            return(CreatedAtRoute("GetTodo", new { id = todo.Id.ToString() }, todo));
        }
Example #30
0
        public ActionResult <Todo> Create(Todo todo)
        {
            _todo.Create(todo);

            return(Ok(todo));
        }