意译。
重构时给你信心
从经验看,即使集中精力进行重构,即便只是给一个变量进行了赋值也可能导致很多问题。没有测试套件,你就不能测试他们。
强制编码必须可测试的方式设计——可以促使你的设计更遵从SOLID原则
[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
[HttpGet]
public ActionResult<UserResponse> Get(int id)
{
var domainUser = UserRepository.GetBy(id);
var responseUser = UserResponseParser.Parse(domainUser);
return Ok(responseUser);
}
}
在大多数情况下,静态类是邪恶的。如果是静态类,则它们不会被注入,这意味着它们不容易被替换。
我们无法对此控制器进行单元测试,因为测试将调用数据库,如果您先编写测试,则不会发生这种情况。
长远看会开发更快
为您提供一种在几秒钟内重新测试应用程序的简便方法
You will often hear, we have no time to write tests, we have no time to do it right. So do you have time to do it twice? The point is if you write a program that does not have automated tests, that will quite likely grow into the point it becomes the spaghetti monster developers take long to fix bugs, as the code is hard to understand and small changes cause magical side-effects.Then the development team will start asking for a rewrite, if they don’t apply TDD the cycle repeats.
你经常听到,我们没时间写测试,我们没时间做正确的事。所以你有时间做两次吗?(ps: 问了作者,作者的意思是有些开发人员因为做事匆忙,并以此为借口不遵循良好的开发原则导致代码越来越难以维护,最后不得不重构)。关键是如果你编写一个没有自动化测试的程序,他很可能会成为一个意大利面怪兽一样,开发人员花很长时间来修复bug,同时代码很难理解,小的变化会导致神奇的副作用。 如果他们没有应用TDD循环重复,于是开发团队将开始要求重写。
那么编写测试首先会减慢开发速度吗?要看怎么理解。没有写测试,你什么时候知道你什么时候完成了开发? 你有信心它有效吗? 它是否涵了盖边缘情况?在尝试扩展应用程序时,如果你能扩展它并且知道你没有破坏以前的行为,那不是很棒吗?
开发周期会更快,从长远来看,随着TDD成为习惯,速度也不会那么不同。(ps:问了作者,没有TDD,一个任务可能需要2小时,如果你第一次使用TDD的话可能需要6小时,但如果你熟练的话,可能恰好也是2小时。关键点在于,在修改代码后,自动化测试会帮你节省大量手动回归的时间)
还要记住,与编写新软件相比,我们作为开发人员的大部分时间都是维护和扩展,因此我们必须对其进行优化。
Minimise YAGNI (You aren't gonna need it) — As developers have clear goals to know when the task is done.
Having a test suite that gives you clear goals so you know when you are finished reduces the guess effort. What will happen on this condition? Instead of wonder, you write a test and define the behaviour you want from it.
It will avoid a lot of unnecessary code.
维护成本降低
如何开始
是否现在就开始写测试用例呢?并不是! TDD首先由Kent Beck提出,他为此指定了三条规则:
- You shall not write production code other than to pass a failing test
- You shall not write more of the production code than necessary to pass that failing test.
- You shall not write more of the test than to make it fail for the right reason.
- 定律一、在编写不能通过的单元测试前,不可编写生产代码。
- 定律二、只可编写刚好无法通过的单元测试,不能编译也算不过。
- 定律三、只可编写刚好足以通过当前失败测试的生产代码。