在谈论单元测试时,“DAMP not DRY"是什么意思? [英] What does “DAMP not DRY” mean when talking about unit tests?

查看:37
本文介绍了在谈论单元测试时,“DAMP not DRY"是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听到有人说单元测试(例如 nUnit、jUnit、xUnit)应该是

I heard someone say that unit tests (e.g. nUnit, jUnit, xUnit) should be

DAMP 不是

(例如,单元测试应该包含湿代码"而不是干代码")

(E.g. unit tests should contain "damp code" not "dry code")

他们在说什么?

推荐答案

这是一种平衡,而不是矛盾

DAMP 和 DRY 并不矛盾,而是平衡了代码可维护性的两个不同方面.可维护的代码(易于更改的代码)是这里的最终目标.

It's a balance, not a contradiction

DAMP and DRY are not contradictory, rather they balance two different aspects of a code's maintainability. Maintainable code (code that is easy to change) is the ultimate goal here.

要维护代码,首先需要了解代码.要理解它,你必须阅读它.考虑一下您花多少时间阅读代码.这是很多.DAMP 通过减少阅读和理解代码所需的时间来提高可维护性.

To maintain code, you first need to understand the code. To understand it, you have to read it. Consider for a moment how much time you spend reading code. It's a lot. DAMP increases maintainability by reducing the time necessary to read and understand the code.

去除重复可确保系统中的每个概念在代码中都有一个单一的权威表示.对单个业务概念的更改会导致对代码的一次更改.DRY 通过将变更(风险)隔离到必须变更的系统部分来提高可维护性.

Removing duplication ensures that every concept in the system has a single authoritative representation in the code. A change to a single business concept results in a single change to the code. DRY increases maintainability by isolating change (risk) to only those parts of the system that must change.

测试通常包含固有的重复,因为它们一遍又一遍地测试相同的东西,只是输入值或设置代码略有不同.但是,与生产代码不同的是,这种重复通常仅与单个测试夹具/文件中的场景隔离.正因为如此,重复是最小的和明显的,这意味着它比其他类型的重复给项目带来的风险更小.

Tests often contain inherent duplication because they are testing the same thing over and over again, only with slightly different input values or setup code. However, unlike production code, this duplication is usually isolated only to the scenarios within a single test fixture/file. Because of this, the duplication is minimal and obvious, which means it poses less risk to the project than other types of duplication.

此外,删除这种重复会降低测试的可读性.以前在每个测试中重复的细节现在隐藏在一些新方法或类中.为了全面了解测试,您现在必须在精神上将所有这些部分重新组合在一起.

Furthermore, removing this kind of duplication reduces the readability of the tests. The details that were previously duplicated in each test are now hidden away in some new method or class. To get the full picture of the test, you now have to mentally put all these pieces back together.

因此,由于测试代码重复通常带来的风险较小,并提高了可读性,因此很容易看出它是如何被认为是可以接受的.

Therefore, since test code duplication often carries less risk, and promotes readability, its easy to see how it is considered acceptable.

原则上,在生产代码中使用 DRY,在测试代码中使用 DAMP.虽然两者同等重要,但只要稍加智慧,您就可以在对自己有利的情况下取得平衡.

这篇关于在谈论单元测试时,“DAMP not DRY"是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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