gpt4 book ai didi

unit-testing - SRP 使类(class)难以测试

转载 作者:行者123 更新时间:2023-12-04 04:23:23 26 4
gpt4 key购买 nike

在重构一些旧的遗留代码时,我尝试尽可能多地应用单一职责原则,所以我最终得到了许多只有一个目的的类。很好,但是当我尝试为这些新类编写单元测试时,问题就来了。有些类(class)真的很难测试,因为测试很难设置。我需要创建大约 4-5 个模拟/ stub 来编写一个测试用例,如果我想覆盖我的所有代码,我需要编写几个测试用例,所以这很麻烦。

很难设置测试(因为它依赖于许多其他类)是一种代码味道吗?你如何解决这个问题?

最佳答案

这是Uncle Bob says about SRP :

A class should have one, and only one, reason to change.

请注意,它并没有说“一个类做一件事而且只做一件事”。换句话说,如果除了其中一项职责以外的所有职责都是不变的,或者如果它们都一起改变,则一个类拥有多个职责是完全有效的。

在他的Agile Patterns, Principles, and Practices书,鲍勃叔叔说:

In the context of SRP, we define a responsibility to be a reason for change (117).

和:

If, on the other hand, the application is not changing in ways that cause [multiple] responsibilities to change at different times, there is no need to separate them. Indeed, separating them would smell of needless complexity. (118)

也就是说,一个有太多协作者的类是一种气味,应该仔细检查。

关于unit-testing - SRP 使类(class)难以测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11784836/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com