是否应该在编写代码之前编写单元测试? [英] Should unit tests be written before the code is written?

查看:36
本文介绍了是否应该在编写代码之前编写单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道测试驱动开发的定义原则之一是首先编写单元测试,然后编写代码以通过这些单元测试,但是否有必要这样做?

I know that one of the defining principles of Test driven development is that you write your Unit tests first and then write code to pass those unit tests, but is it necessary to do it this way?

我发现在编写之前我常常不知道我在测试什么,主要是因为我过去参与的几个项目更多地是从概念验证而不是设计演变而来的.

I've found that I often don't know what I am testing until I've written it, mainly because the past couple of projects I've worked on have more evolved from a proof of concept rather than been designed.

我以前尝试过编写单元测试,它可能很有用,但对我来说似乎并不自然.

I've tried to write my unit tests before and it can be useful, but it doesn't seem natural to me.

推荐答案

这里有一些不错的评论,但我认为有一点被忽略了.

Some good comments here, but I think that one thing is getting ignored.

首先编写测试来驱动您的设计.这是重要的一步.如果您同时"或不久之后"编写测试,您可能会错过在微步骤中执行 TDD 的一些设计优势.

writing tests first drives your design. This is an important step. If you write the tests "at the same time" or "soon after" you might be missing some design benefits of doing TDD in micro steps.

一开始感觉很俗气,但看着事物在您眼前展开,变成您最初没有想到的设计,真是太神奇了.我已经看到它发生了.

It feels really cheesy at first, but it's amazing to watch things unfold before your eyes into a design that you didn't think of originally. I've seen it happen.

TDD 很难,并不适合所有人.但是,如果您已经接受了单元测试,那么请尝试一个月,看看它对您的设计和生产力有何影响.

TDD is hard, and it's not for everybody. But if you already embrace unit testing, then try it out for a month and see what it does to your design and productivity.

您花在调试器上的时间更少,而将更多时间用于考虑由外而内的设计.这是我书中的两个巨大优势.

You spend less time in the debugger and more time thinking about outside-in design. Those are two gigantic pluses in my book.

这篇关于是否应该在编写代码之前编写单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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