NUnit Mock with WinForms Code Review

Define the Basket and BasketItem Objects

Code Review

Code Walkthrough

* Based on NUnit version 2.4.8

The Basket class invokes the LoadBasketItems and SaveBasketItems methods of the IShoppingDataAccess interface.

public class Basket { private List<BasketItem> m_basketItems; private Guid m_basketID; private IShoppingDataAccess m_dataAccessProvider;
public Basket() { this.m_dataAccessProvider = new DataAccessProvider(); this.m_basketItems = new List<BasketItem>(); this.m_basketID = Guid.NewGuid(); } public Basket(IShoppingDataAccess dataAccessProvider) { this.m_dataAccessProvider = dataAccessProvider; this.m_basketItems = new List<BasketItem>(); this.m_basketID = Guid.NewGuid(); }
public void AddItem(BasketItem item) { this.m_basketItems.Add(item); } public Decimal CalculateSubTotal() { Decimal subTotal = 0; foreach (BasketItem item in this.m_basketItems) { subTotal += item.GetPrice(); } return (subTotal); } public List<BasketItem> Load() { return (this.m_basketItems); } public void Save() { this.m_dataAccessProvider.SaveBasketItems(this.m_basketID, this.m_basketItems); } }

Define the BasketItem class, which represents a class to be unit tested.

public class BasketItem { private Int32 m_productID; public String ProductName { get; private set; } public Decimal Quantity { get; set; } public Decimal UnitPrice { get; private set; }
private IShoppingDataAccess m_dataAccessProvider;
public BasketItem(Int32 productID, Int32 quantity) { this.m_dataAccessProvider = new DataAccessProvider(); this.ProductID = productID; this.Quantity = quantity; } public BasketItem(Int32 productID, Int32 quantity, IShoppingDataAccess dataAccessProvider) { this.m_dataAccessProvider = dataAccessProvider; this.ProductID = productID; this.Quantity = quantity; }
public Int32 ProductID { get { return this.m_productID; } set { this.m_productID = value; this.UnitPrice = this.m_dataAccessProvider.GetUnitPrice(this.m_productID); this.ProductName = this.m_dataAccessProvider.GetProductName(this.m_productID); } }
public Decimal GetPrice() { return (this.UnitPrice * this.Quantity); } }

Define two constructors; first a default constructor with two input parameters and a second constructor accepting the IShoppingDataAccess interface type as an input parameter. The second constructor will be used by the mocking objects when running the unit tests.

The BasketItem class invokes the GetProductName and GetUnitPrice methods of the IShoppingDataAccess interface.