public void CanRetreiveImageData() { Game game = new Game { GameId = 2, Name = "Game 2", ImageData = new byte[] { }, ImageMimeType = "image/png" }; Mock<IGameRepository> mock = new Mock<IGameRepository>(); mock.Setup(m => m.Games).Returns(new List<Game> { new Game {GameId = 1, Name = "Game 1"}, game, new Game {GameId = 3, Name = "Game 3"} }.AsQueryable()); GameController controller = new GameController(mock.Object); ActionResult result = controller.GetImage(2); Assert.IsNotNull(result); Assert.IsInstanceOfType(result, typeof(FileResult)); Assert.AreEqual(game.ImageMimeType, ((FileResult)result).ContentType); }
public void CanSaveValidChanges() { Mock<IGameRepository> mock = new Mock<IGameRepository>(); AdminController controller = new AdminController(mock.Object); Game game = new Game { Name = "Test" }; ActionResult result = controller.Edit(game); mock.Verify(m => m.SaveGame(game)); Assert.IsNotInstanceOfType(result, typeof(ViewResult)); }
public void CannotSaveInvalidChanges() { Mock<IGameRepository> mock = new Mock<IGameRepository>(); AdminController controller = new AdminController(mock.Object); Game game = new Game { Name = "Test" }; controller.ModelState.AddModelError("error", "error"); ActionResult result = controller.Edit(game); mock.Verify(m => m.SaveGame(It.IsAny<Game>()), Times.Never()); Assert.IsInstanceOfType(result, typeof(ViewResult)); }
public void CalculateTotalCart() { Game game1 = new Game { GameId = 1, Name = "Game 1", Price = 100 }; Game game2 = new Game { GameId = 2, Name = "Game 2", Price = 200 }; Cart cart = new Cart(); cart.AddItem(game1, 1); cart.AddItem(game2, 1); cart.AddItem(game1, 5); decimal totalCost = cart.ComputeTotalValue(); Assert.AreEqual(totalCost, 800); }
public ActionResult Edit(Game game) { if (ModelState.IsValid) { repository.SaveGame(game); TempData["message"] = string.Format("Изменения в игре \"{0}\" были сохранены", game.Name); return RedirectToAction("Index"); } else { // Что-то не так со значениями данных return View(game); } }
public void CanAddNewLines() { Game game1 = new Game { GameId = 1, Name = "Game 1" }; Game game2 = new Game { GameId = 2, Name = "Game 2" }; Cart cart = new Cart(); cart.AddItem(game1, 2); cart.AddItem(game2, 1); List<CartLine> res = cart.Lines.ToList(); Assert.AreEqual(res.Count, 2); Assert.AreEqual(res[0].Game, game1); Assert.AreEqual(res[1].Game, game2); }
public void CanAddQuantityForExitingLines() { Game game1 = new Game { GameId = 1, Name = "Game 1" }; Game game2 = new Game { GameId = 2, Name = "Game 2" }; Cart cart = new Cart(); cart.AddItem(game1, 1); cart.AddItem(game2, 1); cart.AddItem(game1, 5); List<CartLine> results = cart.Lines.OrderBy(c => c.Game.GameId).ToList(); Assert.AreEqual(results.Count(), 2); Assert.AreEqual(results[0].Quantity, 6); Assert.AreEqual(results[1].Quantity, 1); }
public void CanRemoveLine() { Game game1 = new Game { GameId = 1, Name = "Game 1" }; Game game2 = new Game { GameId = 2, Name = "Game 2" }; Game game3 = new Game { GameId = 3, Name = "Game 3" }; Cart cart = new Cart(); cart.AddItem(game1, 1); cart.AddItem(game2, 1); cart.AddItem(game1, 5); cart.AddItem(game3, 2); cart.RemoveLine(game2); Assert.AreEqual(cart.Lines.Count(), 2); Assert.AreEqual(cart.Lines.Where(g => g.Game == game2).Count(), 0); }
public void SaveGame(Game game) { if (game.GameId == 0) context.Games.Add(game); else { Game dbEntry = context.Games.Find(game.GameId); if (dbEntry != null) { dbEntry.Name = game.Name; dbEntry.Description = game.Description; dbEntry.Price = game.Price; dbEntry.Category = game.Category; } } context.SaveChanges(); }
public void Calculate_Cart_Total() { // Организация - создание нескольких тестовых игр Game game1 = new Game { GameId = 1, Name = "Игра1", Price = 100 }; Game game2 = new Game { GameId = 2, Name = "Игра2", Price = 55 }; // Организация - создание корзины Cart cart = new Cart(); // Действие cart.AddItem(game1, 1); cart.AddItem(game2, 1); cart.AddItem(game1, 5); decimal result = cart.ComputeTotalValue(); // Утверждение Assert.AreEqual(result, 655); }
public void AddItem(Game game, int quantity) { CartLine lines = _lineCollection .Where(g => g.Game.GameId == game.GameId) .FirstOrDefault(); if(lines == null) { _lineCollection.Add(new CartLine { Game = game, Quantity = quantity }); } else { lines.Quantity += quantity; } }
public ActionResult Edit(Game game, HttpPostedFileBase image = null) { if(ModelState.IsValid) { if (image != null) { game.ImageMimeType = image.ContentType; game.ImageData = new byte[image.ContentLength]; image.InputStream.Read(game.ImageData, 0, image.ContentLength); } _repository.SaveGame(game); TempData["message"] = string.Format("Changes is the game \"{0}\" was saved", game.Name); return RedirectToAction("Index"); } else { return View(game); } }
public void Can_Add_New_Lines() { // Организация - создание нескольких тестовых игр Game game1 = new Game { GameId = 1, Name = "Игра1" }; Game game2 = new Game { GameId = 2, Name = "Игра2" }; // Организация - создание корзины Cart cart = new Cart(); // Действие cart.AddItem(game1, 1); cart.AddItem(game2, 1); List<CartLine> results = cart.Lines.ToList(); // Утверждение Assert.AreEqual(results.Count(), 2); Assert.AreEqual(results[0].Game, game1); Assert.AreEqual(results[1].Game, game2); }
public ActionResult Edit(Game game, HttpPostedFileBase image = null) { if (ModelState.IsValid) { if (image != null) { game.ImageMimeType = image.ContentType; game.ImageData = new byte[image.ContentLength]; image.InputStream.Read(game.ImageData, 0, image.ContentLength); } repository.SaveGame(game); TempData["message"] = string.Format("Изменения в игре \"{0}\" были сохранены", game.Name); return RedirectToAction("Index"); } else { // Что-то не так со значениями данных return View(game); } }
public void Can_Add_Quantity_For_Existing_Lines() { // Организация - создание нескольких тестовых игр Game game1 = new Game { GameId = 1, Name = "Игра1" }; Game game2 = new Game { GameId = 2, Name = "Игра2" }; // Организация - создание корзины Cart cart = new Cart(); // Действие cart.AddItem(game1, 1); cart.AddItem(game2, 1); cart.AddItem(game1, 5); List<CartLine> results = cart.Lines.OrderBy(c => c.Game.GameId).ToList(); // Утверждение Assert.AreEqual(results.Count(), 2); Assert.AreEqual(results[0].Quantity, 6); // 6 экземпляров добавлено в корзину Assert.AreEqual(results[1].Quantity, 1); }
public void SaveGame(Game game) { if(game.GameId == 0) { _context.Games.Add(game); } else { Game entryGame = _context.Games.Find(game.GameId); if(entryGame != null) { entryGame.Name = game.Name; entryGame.Description = game.Description; entryGame.Category = game.Category; entryGame.Price = game.Price; entryGame.ImageData = game.ImageData; entryGame.ImageMimeType = game.ImageMimeType; } } _context.SaveChanges(); }
public void Cannot_Save_Invalid_Changes() { // Организация - создание имитированного хранилища данных Mock<IGameRepository> mock = new Mock<IGameRepository>(); // Организация - создание контроллера AdminController controller = new AdminController(mock.Object); // Организация - создание объекта Game Game game = new Game { Name = "Test" }; // Организация - добавление ошибки в состояние модели controller.ModelState.AddModelError("error", "error"); // Действие - попытка сохранения товара ActionResult result = controller.Edit(game); // Утверждение - проверка того, что обращение к хранилищу НЕ производится mock.Verify(m => m.SaveGame(It.IsAny<Game>()), Times.Never()); // Утверждение - проверка типа результата метода Assert.IsInstanceOfType(result, typeof(ViewResult)); }
public void TestInitialize() { var dota = new Game { Id = 1, Name = "Dota 2", Description = "Just try it", Key = "dota-2" }; var games = new[] { dota }; var innerComment = new Comment { Id = 2, Name = "Second author", Body = "Inner comment" }; var comment = new Comment { Id = 1, Name = "First author", Body = "Outer comment", Game = dota, GameId = dota.Id, ChildComments = new[] { innerComment } }; _createCommentCommand = new CreateCommentCommand { Name = "New name", Body = "New body", GameId = 1 }; innerComment.ParentComment = comment; innerComment.ParentCommentId = comment.Id; _comments = new[] { comment, innerComment }; _gameRepositoryMock = new Mock<IRepository<Game, int>>(); _gameRepositoryMock.Setup(x => x.GetSingle(It.IsAny<Expression<Func<Game, Boolean>>>())).Returns( (Expression<Func<Game, Boolean>> predicate) => games.FirstOrDefault(predicate.Compile())); _gameRepositoryMock.Setup(x => x.Get(It.Is<Int32>(i => i == 1))).Returns(dota); _commentRepositoryMock = new Mock<IRepository<Comment, int>>(); _commentRepositoryMock.Setup(x => x.Get(It.IsAny<Expression<Func<Comment, Boolean>>>())).Returns( (Expression<Func<Comment, Boolean>> predicate) => _comments.Where(predicate.Compile())); _commentRepositoryMock.Setup(x => x.Get(It.IsAny<Int32>())).Returns( (Int32 i) => _comments.FirstOrDefault(c => c.Id == i)); _unitOfWorkMock = new Mock<IGameStoreUnitOfWork>(); _unitOfWorkMock.Setup(x => x.Games).Returns(_gameRepositoryMock.Object); _unitOfWorkMock.Setup(x => x.Comments).Returns(_commentRepositoryMock.Object); ILogger logger = new Mock<ILogger>().Object; _queryHandler = new CommentQueryHandler(_unitOfWorkMock.Object, logger); _commandHandler = new CommentCommandHandler(_unitOfWorkMock.Object, logger); }
public void ClearCart() { Game game1 = new Game { GameId = 1, Name = "Game 1", Price = 100 }; Game game2 = new Game { GameId = 2, Name = "Game 2", Price = 200 }; Cart cart = new Cart(); cart.AddItem(game1, 1); cart.AddItem(game2, 1); cart.AddItem(game1, 5); cart.Clear(); Assert.AreEqual(cart.Lines.Count(), 0); }
public void TestInializer() { var rts = new Genre { Id = 1, Name = "RTS", ChildGenres = new Genre[0] }; var strategy = new Genre { Id = 2, Name = "Strategy", ChildGenres = new[] { rts } }; rts.ParentGenre = strategy; rts.ParentGenreId = 2; var genres = new[] { rts, strategy }; _genreRepositoryMock = new Mock<IRepository<Genre, int>>(); _genreRepositoryMock.Setup(x => x.Get()).Returns(genres); _genreRepositoryMock.Setup(x => x.Get(It.IsAny<Int32>())).Returns( (Int32 i) => genres.FirstOrDefault(g => g.Id == i)); _genreRepositoryMock.Setup(x => x.GetSingle(It.IsAny<Expression<Func<Genre, Boolean>>>())).Returns( (Expression<Func<Genre, Boolean>> predicate) => genres.FirstOrDefault(predicate.Compile())); var desktop = new PlatformType { Id = 1, Name = "Desktop" }; var web = new PlatformType { Id = 2, Name = "Web" }; var platformTypes = new[] { desktop, web }; _platformTypeRepositoryMock = new Mock<IRepository<PlatformType, int>>(); _platformTypeRepositoryMock.Setup(x => x.Get()).Returns(platformTypes); _platformTypeRepositoryMock.Setup(x => x.Get(It.IsAny<Int32>())).Returns( (Int32 i) => platformTypes.FirstOrDefault(g => g.Id == i)); _platformTypeRepositoryMock.Setup(x => x.GetSingle(It.IsAny<Expression<Func<PlatformType, Boolean>>>())).Returns( (Expression<Func<PlatformType, Boolean>> predicate) => platformTypes.FirstOrDefault(predicate.Compile())); _platformTypeRepositoryMock.Setup(x => x.Get(It.IsAny<Expression<Func<PlatformType, Boolean>>>())).Returns( (Expression<Func<PlatformType, Boolean>> predicate) => platformTypes.Where(predicate.Compile())); _newGameRightCommand = new CreateGameCommand { Name = "GTA 5", Description = "5 part", Key = "gta-5", GenreIds = new[] { 1 }, PlatformTypeIds = new[] { 1 } }; _editGameRightCommand = new EditGameCommand { Id = 1, Name = "New name", Description = "New description", Key = "new-key", GenreIds = new[] { 2 }, PlatformTypeIds = new[] { 2 } }; _dota = new Game { Id = 1, Name = "Dota 2", Description = "Just try it", Key = "dota-2", Genres = new[] { rts }, PlatformTypes = new[] { desktop, web } }; _witcher = new Game { Id = 2, Name = "Witcher 3", Description = "3d part of trilogy", Key = "witcher-3", Genres = new[] { strategy }, PlatformTypes = new[] { desktop } }; _games = new[] { _dota, _witcher }; _gameRepositoryMock = new Mock<IRepository<Game, int>>(); _gameRepositoryMock.Setup(x => x.Get()).Returns(_games); _gameRepositoryMock.Setup(x => x.Get(It.Is<Int32>(i => i == 1))).Returns(_dota); _gameRepositoryMock.Setup(x => x.Get(It.Is<Int32>(i => i == 2))).Returns(_witcher); _gameRepositoryMock.Setup(x => x.Get(It.IsAny<Expression<Func<Game, Boolean>>>())).Returns( (Expression<Func<Game, Boolean>> predicate) => _games.Where(predicate.Compile())); _gameRepositoryMock.Setup(x => x.GetSingle(It.IsAny<Expression<Func<Game, Boolean>>>())).Returns( (Expression<Func<Game, Boolean>> predicate) => _games.FirstOrDefault(predicate.Compile())); _unitOfWorkMock = new Mock<IGameStoreUnitOfWork>(); _unitOfWorkMock.Setup(x => x.Games).Returns(_gameRepositoryMock.Object); _unitOfWorkMock.Setup(x => x.Genres).Returns(_genreRepositoryMock.Object); _unitOfWorkMock.Setup(x => x.PlatformTypes).Returns(_platformTypeRepositoryMock.Object); var logger = new Mock<ILogger>(); _commandHandler = new GameCommandHandler(_unitOfWorkMock.Object, logger.Object); _queryHandler = new GameQueryHandler(_unitOfWorkMock.Object, logger.Object); }
public void RemoveLine(Game game) { _lineCollection.RemoveAll(l => l.Game.GameId == game.GameId); }
public void Can_Remove_Line() { // Организация - создание нескольких тестовых игр Game game1 = new Game { GameId = 1, Name = "Игра1" }; Game game2 = new Game { GameId = 2, Name = "Игра2" }; Game game3 = new Game { GameId = 3, Name = "Игра3" }; // Организация - создание корзины Cart cart = new Cart(); // Организация - добавление нескольких игр в корзину cart.AddItem(game1, 1); cart.AddItem(game2, 4); cart.AddItem(game3, 2); cart.AddItem(game2, 1); // Действие cart.RemoveLine(game2); // Утверждение Assert.AreEqual(cart.Lines.Where(c => c.Game == game2).Count(), 0); Assert.AreEqual(cart.Lines.Count(), 2); }
public void Can_Delete_Valid_Games() { // Организация - создание объекта Game Game game = new Game { GameId = 2, Name = "Игра2" }; // Организация - создание имитированного хранилища данных Mock<IGameRepository> mock = new Mock<IGameRepository>(); mock.Setup(m => m.Games).Returns(new List<Game> { new Game { GameId = 1, Name = "Игра1"}, new Game { GameId = 2, Name = "Игра2"}, new Game { GameId = 3, Name = "Игра3"}, new Game { GameId = 4, Name = "Игра4"}, new Game { GameId = 5, Name = "Игра5"} }); // Организация - создание контроллера AdminController controller = new AdminController(mock.Object); // Действие - удаление игры controller.Delete(game.GameId); // Утверждение - проверка того, что метод удаления в хранилище // вызывается для корректного объекта Game mock.Verify(m => m.DeleteGame(game.GameId)); }
public void Can_Clear_Contents() { // Организация - создание нескольких тестовых игр Game game1 = new Game { GameId = 1, Name = "Игра1", Price = 100 }; Game game2 = new Game { GameId = 2, Name = "Игра2", Price = 55 }; // Организация - создание корзины Cart cart = new Cart(); // Действие cart.AddItem(game1, 1); cart.AddItem(game2, 1); cart.AddItem(game1, 5); cart.Clear(); // Утверждение Assert.AreEqual(cart.Lines.Count(), 0); }
public void Can_Save_Valid_Changes() { // Организация - создание имитированного хранилища данных Mock<IGameRepository> mock = new Mock<IGameRepository>(); // Организация - создание контроллера AdminController controller = new AdminController(mock.Object); // Организация - создание объекта Game Game game = new Game { Name = "Test" }; // Действие - попытка сохранения товара ActionResult result = controller.Edit(game); // Утверждение - проверка того, что к хранилищу производится обращение mock.Verify(m => m.SaveGame(game)); // Утверждение - проверка типа результата метода Assert.IsNotInstanceOfType(result, typeof(ViewResult)); }