是否应该为 getter 和 setter 编写单元测试? [英] Should unit tests be written for getter and setters?

查看:30
本文介绍了是否应该为 getter 和 setter 编写单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们应该为我们的 getter 和 setter 编写测试还是过度?

Are we supposed to write tests for our getters and setters or is it overkill?

推荐答案

我会说不.

@Will 说你应该以 100% 的代码覆盖率为目标,但在我看来,这是一种危险的分心.您可以编写具有 100% 覆盖率的单元测试,但绝对不进行任何测试.

@Will said you should aim for 100% code coverage, but in my opinion that's a dangerous distraction. You can write unit tests that have 100% coverage, and yet test absolutely nothing.

单元测试是为了以一种富有表现力和有意义的方式测试您的代码的行为,而 getter/setter 只是达到目的的一种手段.如果您的测试使用 getter/setter 来实现他们测试真实"功能的目标,那就足够了.

Unit tests are there to test the behaviour of your code, in an expressive and meaningful way, and getters/setters are only a means to an end. If you tests use the getters/setters to achieve their goal of testing the "real" functionality, then that's good enough.

另一方面,如果你的 getter 和 setter 不仅仅是获取和设置(即它们是非常复杂的方法),那么是的,它们应该被测试.但是不要编写单元测试用例只是来测试 getter 或 setter,那是在浪费时间.

If, on the other hand, your getters and setters do more than just get and set (i.e. they're properly complex methods), then yes, they should be tested. But don't write a unit test case just to test a getter or setters, that's a waste of time.

这篇关于是否应该为 getter 和 setter 编写单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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