发布于 2026-01-06 0 阅读
0

TDD 方法

TDD 方法

多亏了我的妻子,这篇博文源于我们早晨喝茶时的一次谈话。她让我把谈话内容写成一篇博文 :)

  • 首先,你需要对要交付的最小代码单元进行测试(目前这个测试单元还不存在)。

describe 'Arithmetic::Sum' do
  describe '#add' do
   it 'is expected to take 2 and 3 and return 5' do
     expect(subject.add(2,3)).to eq(5)
   end
  end
end

Enter fullscreen mode Exit fullscreen mode
  • 确保测试失败并报错,提示Unit of code您正在测试的对象尚不存在。
 Arithmetic::Sum not found error

Enter fullscreen mode Exit fullscreen mode
  • 开始编写代码……只需编写最少的代码,使测试因你预期的原因而失败即可。

    • 创建算术模块
    • 在该模块内添加类
    • 添加方法add(目前为空)
   Code errors out saying nil and 5 are not equal.
Enter fullscreen mode Exit fullscreen mode
  • 编码时间到……现在编写使测试通过所需的最少代码。
  def add(a, b)
    return 5
  end
Enter fullscreen mode Exit fullscreen mode
  • 此时测试结果应该会变成绿色。
  • 添加一些额外的测试预期,故意使测试失败,并确保失败消息有意义。
 describe 'Arithmetic::Sum' do
  describe '#add' do
   it 'is expected to take 2 and 3 and return 5' do
     expect(subject.add(2,3)).to eq(5)
   end

   it 'is expected to take 4 and 6 and return 10' do
     expect(subject.add(4,6)).to eq(10)
   end

   it 'is expected to take 100 and 100 and return 200' do
     expect(subject.add(100,100)).to eq(200)
   end
  end
 end

Enter fullscreen mode Exit fullscreen mode
  • 正如鲍勃大叔所说,As the Tests get more Specific, the Code gets more Generic应该增强add方法,使其更加通用,能够处理上面提到的所有测试用例。
 module Arithmetic
   class Sum
     def add(a, b)
      return a + b
     end
   end 
 end

Enter fullscreen mode Exit fullscreen mode
  • 再次运行测试,看看所有结果是否都变成绿色。
  • 提交代码吧 :)

这篇博客中的示例遵循了我编写 Ruby 程序时通常采用的 TDD 方法。我很好奇 Java 或 Go 社区是如何运用 TDD 的,因为在运行程序之前,它们都有一个编译阶段。我会进行研究,如果可能的话,我会根据它们的开发社区如何运用 TDD,撰写另一篇后续博客。

感谢鲍勃大叔和他的代码清理视频:)

文章来源:https://dev.to/elitenomad/tdd-approach-g9c