C# Unit testing. Verify list count

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));
    }
}
Jon Skeet
people
quotationmark

There are various options here:

  • Expose 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.
  • Expose 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.)
  • Stick to testing the public API - you can check whether all the rules you add into the list (in your test) are then consulted.

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.

people

See more on this question at Stackoverflow