CalebHC CalebHC - 5 months ago 35
C# Question

Unit Testing Private Setter Question (C#)

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)
return true;

return false;

So here is my problem: how do I set the new Item's private setter Id in the test method so the CheckForDuplicateItem method will work? I don't want to make that member public for good coding practices, I guess. Am I just being stupid and need to make the entity Item have a public Id setter? Or do I need to use reflection? Thanks

Note - I'm using NHibernate for persistence


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.