9.1.1 Creating a Custom Model Binder; UNIT TEST: THE CART CONTROLLER

This commit is contained in:
Jason Zhu 2021-09-18 23:30:33 +10:00
parent 78b4ea3640
commit a8154783e7

View File

@ -2,6 +2,12 @@
using SportsStore.Domain.Entities;
using System;
using System.Linq;
using System.Security.AccessControl;
using System.Web.Mvc;
using Moq;
using SportsStore.Domain.Abstract;
using SportsStore.WebUI.Controllers;
using SportsStore.WebUI.Models;
namespace SportsStore.UnitTests
{
@ -116,5 +122,70 @@ namespace SportsStore.UnitTests
// Assert
Assert.AreEqual(target.Lines.Count(), 0);
}
}
[TestMethod]
public void Can_Add_To_Cart()
{
// Arrange - create the mock repository
Mock<IProductRepository> mock = new Mock<IProductRepository>();
mock.Setup(m => m.Products).Returns(new Product[]
{
new Product { ProductID = 1, Name = "P1", Category = "Apples" },
}.AsQueryable());
// Arrange - create a Cart
Cart cart = new Cart();
// Arrange - create the controller
CartController target = new CartController(mock.Object);
// Act - add a product to the cart
target.AddToCart(cart, 1, null);
// Assert
Assert.AreEqual(cart.Lines.Count(), 1);
Assert.AreEqual(cart.Lines.ToArray()[0].Product.ProductID, 1);
}
[TestMethod]
public void Adding_Product_To_Cart_Goes_To_Cart_Screen()
{
// Arrange - create the mock repository
Mock<IProductRepository> mock = new Mock<IProductRepository>();
mock.Setup(m => m.Products).Returns(new Product[]
{
new Product { ProductID = 1, Name = "P1", Category = "Apples" },
}.AsQueryable());
// Arrange - create a Cart
Cart cart = new Cart();
// Arrange - create the controller
CartController target = new CartController(mock.Object);
// Act - add a product to the
RedirectToRouteResult result = target.AddToCart(cart, 2, "myUrl");
// Assert
Assert.AreEqual(result.RouteValues["action"], "Index");
Assert.AreEqual(result.RouteValues["returnUrl"], "myUrl");
}
[TestMethod]
public void Can_View_Cart_Contents()
{
// Arrange - create a Cart
Cart cart = new Cart();
// Arrange - create the controller
CartController target = new CartController(null);
// Act - call the Index action methdo
CartIndexViewModel result = (CartIndexViewModel)target.Index(cart, "myUrl").ViewData.Model;
// Assert
Assert.AreSame(result.Cart, cart);
Assert.AreEqual(result.ReturnUrl, "myUrl");
}
}
}