单元测试时使用反射还是属性?

编程入门 行业动态 更新时间:2024-10-21 20:29:03
本文介绍了单元测试时使用反射还是属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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 ... } }

什么是最好的:

  • 使用反射检查私有财产,或
  • 既然原始 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.

    更多推荐

    单元测试时使用反射还是属性?

    本文发布于:2023-11-11 07:43:17,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1577784.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:反射   属性   单元测试

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!