چگونه کد قابل تست بنویسیم - قسمت دوم و پایانی
نویسنده: محمد بنازاده
تاریخ: ۱۳۹۳/۱۰/۰۱ ۱۳:۴۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
public interface IShoppingCartService
{
ShoppingCart GetContents();
ShoppingCart AddItemToCart(int itemId, int quantity);
}
public class ShoppingCartService : IShoppingCartService
{
public ShoppingCart GetContents()
{
throw new NotImplementedException("Get cart from Persistence Layer");
}
public ShoppingCart AddItemToCart(int itemId, int quantity)
{
throw new NotImplementedException("Add Item to cart then return updated cart");
}
}
public class ShoppingCart
{
public List<product> Items { get; set; }
}
public class Product
{
public int ItemId { get; set; }
public string ItemName { get; set; }
}
public class ShoppingCartController : Controller
{
//Concrete object below points to actual service
//private ShoppingCartService _shoppingCartService;
//loosely coupled code below uses the interface rather than the
//concrete object
private IShoppingCartService _shoppingCartService;
public ShoppingCartController()
{
_shoppingCartService = new ShoppingCartService();
}
public ActionResult GetCart()
{
//now using the shared instance of the shoppingCartService dependency
ShoppingCart cart = _shoppingCartService.GetContents();
return View("Cart", cart);
}
public ActionResult AddItemToCart(int itemId, int quantity)
{
//now using the shared instance of the shoppingCartService dependency
ShoppingCart cart = _shoppingCartService.AddItemToCart(itemId, quantity);
return View("Cart", cart);
}
} //loosely coupled code below uses the interface rather
//than the concrete object
private IShoppingCartService _shoppingCartService;
//MVC uses this constructor
public ShoppingCartController()
{
_shoppingCartService = new ShoppingCartService();
}
//You can use this constructor when testing to inject the
//ShoppingCartService dependency
public ShoppingCartController(IShoppingCartService shoppingCartService)
{
_shoppingCartService = shoppingCartService;
} [TestClass]
public class ShoppingCartControllerTests
{
[TestMethod]
public void GetCartSmokeTest()
{
//arrange
ShoppingCartController controller =
new ShoppingCartController(new ShoppingCartServiceStub());
// Act
ActionResult result = controller.GetCart();
// Assert
Assert.IsInstanceOfType(result, typeof(ViewResult));
}
}
/// <summary>
/// This is is a stub of the ShoppingCartService
/// </summary>
public class ShoppingCartServiceStub : IShoppingCartService
{
public ShoppingCart GetContents()
{
return new ShoppingCart
{
Items = new List<product> {
new Product {ItemId = 1, ItemName = "Widget"}
}
};
}
public ShoppingCart AddItemToCart(int itemId, int quantity)
{
throw new NotImplementedException();
}
}