I'm trying to test an Order entity method called AddItem and I'm trying to make sure that duplicate items cannot be added. Here is some example code:
public void ItemCannotBeAddedTwiceToOrder()
Order o = new Order();
Item i = new Item("Bike");
Assert.AreEqual(o.ItemCount, 1, "A duplicate item was added.");
public void AddItem(Item newItem)
public bool CheckForDuplicateItem(Item newItem)
foreach(Item i in _items)
if(i.Id == newItem.Id)
I usually use reflection for this purpose. Something like this will work:
typeof(Item).GetProperty("Id").SetValue(i, 1, null);
where 1 is the id that you want to set for the newItem instance.
In my experience, you'll rarely need to set the Id, so it's better just to leave the setter private. In the few cases that you do need to set the Id for testing purposes, simply use Reflection.