This is my first question so please be kind! 🙂
What I am trying to do is write some tests for a manager class that during construction adds many new instances of a single item class to a list. When the UpdateAllItems is called in this manager class the intention is to iterate the list and call Increment on each single item.
The manager class is my code, but the single item class is not so I can’t modify it.
I use NUnit for a testing framework and am starting to work with Moq. Because the manager class uses the single item class I would think I need to use a Moq so I am testing only the manager, not the single item.
How do I write tests for my UpdateAllItems method? (Technically I should be writing the tests first I know).
Here is a some sample code that gives a general idea of what I am working with…
public class SingleItem_CodeCantBeModified
{
public int CurrentValue { get; private set; }
public SingleItem_CodeCantBeModified(int startValue)
{
CurrentValue = startValue;
}
public void Increment()
{
CurrentValue++;
}
}
public class SingleItemManager
{
List<SingleItem_CodeCantBeModified> items = new List<SingleItem_CodeCantBeModified>();
public SingleItemManager()
{
items.Add(new SingleItem_CodeCantBeModified(100));
items.Add(new SingleItem_CodeCantBeModified(200));
}
public void UpdateAllItems()
{
items.ForEach(item => item.Increment());
}
}
Thanks in advance for all the help!
The simple answer is, you can’t. The method that
UpdateAllItemscalls (Increment()) is non-virtual, so you won’t be able to mock it.Your options, as I see it, are:
UpdateAllItemsat all. Its implementation is trivial, so this is an option to consider (though not ideal).SingleItem_CodeCantBeModifiedinstances in your test. Purists would say that you no longer have a unit test at this point, but it could still be a useful test.ISingleIteminterface, and anSingleItemAdapter : ISingleItemclass that holds onto a reference to aSingleItem_CodeCantBeModifiedand forwards the calls. Then you can writeSingleItemManagerto operate onISingleItems, and you’ll be free to pass in mockISingleItems in your tests. (Depending on how your system is set up, you might even be able to descend fromSingleItem_CodeCantBeModified, implement the interface on your descendant, and use those objects instead of writing an adapter.)That last option gives you the most options, but at the cost of some complexity. Choose the option that’s best suited for what you’re trying to accomplish.