[英]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. 我想要一个测试用例,可以验证随着新增的IRule项,IRule计数列表增加。 The method I am testing is AddRule.
我正在测试的方法是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));
}
}
You could expose a Count
read only property that returns the count of rules
: 您可以公开一个
Count
只读属性,该属性返回rules
的计数:
public int RulesCount
{
get { return rules.Count; }
}
There are various options here: 这里有多种选择:
rules
publicly but safely, eg via a ReadOnlyCollection<T>
wrapper or as an IEnumerable<IRule>
via return rules.Select(r => r);
rules
,例如通过ReadOnlyCollection<T>
包装器或通过return rules.Select(r => r);
作为IEnumerable<IRule>
return rules.Select(r => r);
to avoid the actual list being exposed via casting. AddRule
. 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. rules
(最好是通过属性公开-我不建议使用内部字段;我还将字段设置为只读),并使用InternalsVisibleTo
允许您的测试访问该字段。 (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. 就我个人而言,我可能会选择前一种方法-但有些人将“仅测试公共API”作为永不中断的黄金法则。
Yet another idea, on the top of previous answers is to perform your unit tests against a class which inherits DefaultRulesManager
. 在先前答案的顶部,还有一个想法是对继承
DefaultRulesManager
的类执行单元测试。
You'd have to change DefaultRulesManager
class slightly by making rules
member protected
. 您必须通过使
rules
成员protected
稍微更改DefaultRulesManager
类。 Inherited class can be named DefaultRulesManagerTestable
and provide public readonly property RulesCount
which would return rules.Count
. 继承的类可以命名为
DefaultRulesManagerTestable
并提供公共只读属性RulesCount
,该属性将返回rules.Count
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.