你是在编写一个功能之前还是之后编写单元测试? [英] Do you write your unit tests before or after coding a piece of functionality?

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

问题描述

我想知道大多数人是什么时候编写单元测试的,如果有的话.我通常在编写初始代码后编写测试,以确保它按预期工作.然后我修复坏掉的东西.

I was wondering when most people wrote their unit tests, if at all. I usually write tests after writing my initial code to make sure it works like its supposed to. I then fix what is broken.

我用这种方法取得了相当大的成功,但一直想知道改用先编写测试是否有利?

I have been pretty successful with this method but have been wondering if maybe switching to writing the test first would be advantageous?

推荐答案

只要有可能,我都会尝试遵循纯 TDD 方法:

whenever possible i try to follow a pure TDD approach:

  1. 为正在开发的功能编写单元测试;这迫使我决定公共接口
  2. 尽快对功能进行编码(尽可能简单,但不要更简单)
  3. 更正/重构/重新测试
  4. 额外测试如果需要以获得更好的覆盖范围、特殊路径等.[罕见但值得考虑]
  5. 重复下一个功能
  1. write the unit tests for the feature being developed; this forces me to decide on the public interface(s)
  2. code the feature ASAP (as simple as possible, but not simpler)
  3. correct/refactor/retest
  4. additional tests if required for better coverage, exceptional paths, etc. [rare but worth consideration]
  5. repeat with next feature

很容易兴奋并首先开始编写功能,但这通常意味着您不会提前考虑所有公共接口.

it is easy to get excited and start coding the feature first, but this often means that you will not think through all of the public interfaces in advance.

请注意,如果您先编写代码,很容易无意编写测试以符合代码,而不是相反!

note that if you write the code first, it is easy to unintentionally write the test to conform to the code, instead of the other way 'round!

这篇关于你是在编写一个功能之前还是之后编写单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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