I wanted to have a test case where I can verify a list of IRule count increases as new IRule item added. The method I am testing is AddRule. I wanted to keep the 'rules' property private.
Here's the code
public class DefaultRulesManager : IRulesManager
{
private List<IRule> rules;
public DefaultRulesManager()
{
rules = new List<IRule>();
}
public void AddRule(IRule rule)
{
if (rule == null)
{
throw new ArgumentNullException("rule must be set");
}
rules.Add(rule);
}
public bool HasPassed<T, SKU>(T obj, SKU s)
{
IProduct product = (IProduct)obj;
return rules.All(x => x.HasPassed(product, s));
}
}
There are various options here:
rules
publicly but safely, e.g. via a ReadOnlyCollection<T>
wrapper or as an IEnumerable<IRule>
via return rules.Select(r => r);
to avoid the actual list being exposed via casting. This is reasonable if you have no objection to callers knowing what rules are in a manager, so long as they can't modify the list except via AddRule
.rules
internally (ideally via a property - I wouldn't suggest an internal field; I'd also make the field readonly), and use InternalsVisibleTo
to allow your test access to that. (You could expose just the count if you want, but I'm not sure it's particularly beneficial.)Personally I'd probably go for the former option - but some people take "only test the public API" as a golden rule never to be broken.
See more on this question at Stackoverflow