[译] 为何TDD会改开发人员的生活

原文:medium.com/@raphaelyos…html

意译。数据库

重构时给你信心

从经验看,即便集中精力进行重构,即使只是给一个变量进行了赋值也可能致使不少问题。没有测试套件,你就不能测试他们。api

强制编码必须可测试的方式设计——能够促使你的设计更听从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);
  }
}
复制代码

在大多数状况下,静态类是邪恶的。若是是静态类,则它们不会被注入,这意味着它们不容易被替换。bash

咱们没法对此控制器进行单元测试,由于测试将调用数据库,若是您先编写测试,则不会发生这种状况。app

长远看会开发更快

为您提供一种在几秒钟内从新测试应用程序的简便方法

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.dom

你常常听到,咱们没时间写测试,咱们没时间作正确的事。因此你有时间作两次吗?(ps: 问了做者,做者的意思是有些开发人员由于作事匆忙,并以此为借口不遵循良好的开发原则致使代码愈来愈难以维护,最后不得不重构)。关键是若是你编写一个没有自动化测试的程序,他极可能会成为一个意大利面怪兽同样,开发人员花很长时间来修复bug,同时代码很难理解,小的变化会致使神奇的反作用。 若是他们没有应用TDD循环重复,因而开发团队将开始要求重写。ide

那么编写测试首先会减慢开发速度吗?要看怎么理解。没有写测试,你何时知道你何时完成了开发? 你有信心它有效吗? 它是否涵了盖边缘状况?在尝试扩展应用程序时,若是你能扩展它而且知道你没有破坏之前的行为,那不是很棒吗?单元测试

开发周期会更快,从长远来看,随着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.

ps: 专门搜了一下,tdd三原则是 uncle bob 提出的,出处:link1, link2

  • 定律1、在编写不能经过的单元测试前,不可编写生产代码。
  • 定律2、只可编写恰好没法经过的单元测试,不能编译也算不过。
  • 定律3、只可编写恰好足以经过当前失败测试的生产代码。

其余资料

相关文章
相关标签/搜索