测试驱动开发:红、绿、重构

在读Ruby on Rails Tutorial: Learn Rails by example 过程中,发现有很多不错的观点,记录并翻译一下,英文不好,请见谅。

 

测试驱动开发:红、绿、重构

TDD: Red, Green, Refactor

 

在测试驱动开发过程中,我们首先写一个不能通过的测试。我们的例子中,要写一段验证“应该是关于”页面的测试代码,(译注:当然,这个时候 about page并没有实现,如果运行测试的话,应该会失败掉,红!)然后,要使测试代码通过的话,就要在我们的例子里就要实现关于页面的行为和视图。那为什么我 们不反过来,先写功能,再测试呢?这是我们要确保测试代码真的测试了我们后来加上的功能。在我刚刚开始使用TDD的时候,我非常惊奇的发现我的测试会捕获 那么多的错误,哪怕测试什么都没有做。当测试用例先失败,再通过,如此反复,对测试代码做了正确的测试就越来越有信心了。

In test-driven development, we first write a failing test: in our case, a piece of code that expresses the idea that there “should be an about ” page. Then we get the test to pass, in our case by adding the about action and corresponding view. The reason we don’t typically do the reverse—implement first, then test—is to make sure that we actually test for the feature we’re adding. Before I started using TDD, I was amazed to discover how often my “tests” actually tested the wrong thing, or even tested nothing at all. By making sure that the test fails first and then passes, we can be more confident that the test is doing the right thing.

 

还有重要的一点是,TDD并不是什么时候都适用的。特别是当为了探查或者解决某种不确定的问题而要快速实现一些功能时,往往会忽略测试代码而直接完成功能代码。(在极限编程中,这种探索性调研的步骤被称为spike ),只有当你确定了问题的解决方案后,你可以使用TDD来实现一个更优雅的版本。

It’s important to understand that TDD is not always the right tool for the job. In particular, when you aren’t at all sure how to solve a given programming problem, it’s often useful to skip the tests and write only application code, just to get a sense of what the solution will look like. (In the language of Extreme Programming (XP) , this exploratory step is called a spike .) Once you see the general shape of the solution, you can then use TDD to implement a more polished version.

 

“红, 绿,重构”是一个在测试驱动开发中使用的方法,第一步,红,意味着写出不能通过的测试(译注:即先写测试,而功能代码未实现),有很多测试工具或以显示错 误为红色。第二步,绿,意味着测试通过(译注:实现功能代码,以便让测试代码可以通过)。当测试通过之后,我们就可以在不影响功能正确的基础上,进行代码 重构(比如,去除重复代码)。

One way to proceed in test-driven development is a cycle known as “Red, Green, Refactor”. The first step, Red, refers to writing a failing test, which many test tools indicate with the color red. The next step, Green, refers to a passing test, indicated with the color (wait for it) green. Once we have a passing test (or set of tests), we are free to refactor our code, changing the form (eliminating duplication, for example) without changing the function.

 

原文引自:http://ruby.railstutorial.org/chapters/static-pages#top

你可能感兴趣的:(技术)