NUnit using NMock Code Review
Define the Basket and BasketItem Objects
Code Review
- NUnit using NMock Code Review: Define the DataAccess Interface
- NUnit using NMock Code Review: Define the Basket and BasketItem Objects
- NUnit using NMock Code Review: Define the Form Test Fixture Class
Code Walkthrough
* Based on NUnit version 2.4.8
Define the Basket class, which represents a class to be unit tested.
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 two constructors; first a default constructor with no 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 Basket class invokes the LoadBasketItems and SaveBasketItems methods of the IShoppingDataAccess interface.
Define the BasketItem class, which represents a class to be unit tested. 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.
private IShoppingDataAccess m_dataAccessProvider;
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); } }
The BasketItem class invokes the GetProductName and GetUnitPrice methods of the IShoppingDataAccess interface.
Printer Friendly Version
Add to Favourites
DotNet Kicks
Digg
del.icio.us
Live Favourites
ma.gnolia
reddit
Slashdot
Technorati
Yahoo!