单元测试时使用反射还是属性? [英] Use reflection or a property when unit testing?

查看:49
本文介绍了单元测试时使用反射还是属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个我有点担心的课程.我的目标是对地址列表进行单元测试:

This is a class I'm a bit concerned about. My goal is to unit test the addresses list:

public class LabelPrinter
{
    private readonly IEnumerable<Address> _addresses;

    public LabelPrinter(IEnumerable<Address> addresses)
    {
        _addresses = addresses;
    }

    public Document Create()
    {
        // ... Generate PDF, etc ...
    }
}

什么是最好的:

  1. 使用反射检查私有财产,或
  2. 既然原始 IEnumerable 无论如何都可以从外部修改,那么制作一个公共 getter 并对其进行测试?

推荐答案

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

In general, private members shouldn't be unit tested, since anything the class is doing with it's private members should somehow be reflected in the externally testable behavior of the object. In other words, who cares what's going on in there, as long as its external behavior is what it should be.

单元测试私有成员还会将您的测试与类的内部联系起来,使它们更加脆弱.如果您决定稍后使用更高效的集合,即使对象的行为没有改变,您的测试也会中断.您尤其希望避免反射,因为按名称查找属性意味着如果属性名称发生更改,您的测试就会中断.

Unit testing private members also couples your tests to the internals of a class, making them more brittle. If you decide to use a more efficient collection later down the road, your tests will break, even though the behavior of the object hasn't changed. You especially want to avoid reflection, since looking up properties by name means your tests break if the property name ever changes.

换句话说 - 如果您需要测试 Address 类,请从它自己的单元测试中进行,而不是从 LabelPrinter 的测试中进行.如果您必须使用两种方法中的一种,请使用第二种,而不是反射.

In other words - if you need to test the Address class, do it from its own unit tests, rather than from the LabelPrinter's tests. If you must use one of your two methods, use the second one, rather than reflection.

这篇关于单元测试时使用反射还是属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆