单元测试——无用的测试怎么了?
我见过人们为一些理所当然的事情编写单元测试。例如:
class Employee
{
public int Id { get; set; }
public string Name { get; set; }
//.....
}
单元测试:
Assert.AreEqual(new Employee().Id, 0);
似乎是对时间和资源的巨大浪费,但有些人确实编写了这样的测试。我什至在微软的一些示例中看到过它。
我错过了什么吗?
I've seen people write unit tests for things that should simply be taken for granted. E.g.:
class Employee
{
public int Id { get; set; }
public string Name { get; set; }
//.....
}
Unit test:
Assert.AreEqual(new Employee().Id, 0);
Seems like a massive waste of time and resources, yet some people do write tests like this. I've even seen it in some samples from Microsoft.
Am I missing something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它们应该针对行为,因此这个默认值为 0 的测试是毫无意义的,除非有原因需要它以这种方式运行,例如堆栈开始为空。
they should be targeted at behaviour, so this test that the default is 0 is pretty pointless unless there is a reason you need it to behave that way, for example a stack starting empty.
单元测试的一大好处是能够快速检测回归。如果开发人员花了数年时间修改 Id getter 函数以返回 Id 以外的值,或者修改默认构造函数以将 Id 设置为非零值,则该测试将会失败。这比几周后发生的一些不起眼的错误更容易调试,因为有代码假设新员工 ID 的初始值为 0。
A big benefit of unit testing is the ability to quickly detect regressions. If a developer comes in years down the track and modifies the Id getter function to return something other than Id or modifies the default constructor to set the Id to something other than zero, that test will fail. That's a lot easier to debug than some obscure bug occuring weeks down the track because there was code assuming the initial value of a new Employee's Id was 0.
单元测试永远不会浪费。如果另一个程序员决定编辑 Id 的 getter 代码怎么办?除非执行单元测试并且它告诉您出了什么问题,否则您永远不会轻易发现这一点。
Unittests are never a waste. What if another programmer decides to edit the getter code for Id? You would never find that out easily unless the unit test is executed and it shows you what's wrong.