unit testing时使用reflection或属性?

这是我有点担心的课程。 我的目标是对地址列表进行unit testing:

public class LabelPrinter { private readonly IEnumerable
_addresses; public LabelPrinter(IEnumerable
addresses) { _addresses = addresses; } public Document Create() { // ... Generate PDF, etc ... } }

什么是最好的:

  1. 使用reflection检查私有财产,或
  2. 既然最初的IEnumerable可以从外部修改,那么做一个公共的getter并测试它呢?

一般来说,私有成员不应该进行unit testing,因为类的私有成员所做的任何事情都应该以某种方式反映在对象的外部可测试行为中。 换句话说,谁在乎那里发生了什么,只要它的外在行为是应该的。

对私人成员进行unit testing也会将您的测试与课堂内部相结合,使其更加脆弱。 如果您决定稍后使用更高效的集合,即使对象的行为没有改变,您的测试也会中断。 您尤其希望避免reflection,因为按名称查找属性意味着如果属性名称发生更改,则测试会中断。

换句话说 – 如果你需要测试Address类,可以从它自己的unit testing中进行,而不是从LabelPrinter的测试中进行。 如果必须使用两种方法中的一种,请使用第二种方法,而不是reflection。

你想在这里测试一下addresses列表? 在上面提供的示例代码中,您的工作实际上非常简单,因为您可以通过构造函数注入列表。 因此,在您的测试中,您可以访问列表,因此不一定需要再次公开它:

 [Test] public void Test() { IEnumerable
addresses = new List
(); LabelPrinter printer = new LabelPrinter(addresses); ... // execute your test here Assert.AreEqual(blah, addresses.get(0)); // or any other assertion you want to make on the addresses list // created up above. }

特别是在学习unit testing的过程中,通过简单的测试和更好的覆盖来超越对保持字段保密的担忧。 选项2。

测试Create而不是设置器(这实际上是你在这里)。 我发现测试设置者/吸气剂有点浪费时间。 ESP。 因为大多数时候必须执行setter才能进行其他测试。 它们在很大程度上也太简单而不能失败。

因此,不要validationLabelPrinter是否具有_addresses并且它是Y,请检查Create的输出是否包含相关详细信息。