Dec 23, 2008

TDD and BDD

Update1: I found I misunderstanded TDD, now I confused with BDD again :(see comments below)

Update2: Someone asked me that why we should write tests first? If we write tests immediately after implement a function, what we lose compare to write test first? My answer is simple: how can you know you test will fail before you write the implementation if you don't write test at first? And how can you make sure it's your code made the test pass, not because the test will pass even without your code?

What's the differences between TDD and BDD? That's always a good candidate question for you recruiting :) It's hard to get the answer from their boring description, at least hard to me.

Today I found a good example to demonstrate the diff between them - Rails validations. For those who don't use rails, validations is used to guard data correctness, for example, if I wrote this in my rails app:

class Book < style="font-style: italic;"> validates_presence_of :title
end

it will always check the Book's title is not blank when save the object. Now the problem is, should you write tests/assertions for this statement?

TDD will say no. Rails is released with lots of tests, the validation's correctness has already been guaranteed by it, in other words your own tests are just duplicate works. But from BDDer's POV, you should write tests for it - to describe the Book's *behavior*, not to cover the validation's implementation code.

So, BDD want to make sure we implemented the right behavior, or function/feature/whatever. If you refactor your code one month later, those seems redundant tests will guarantee your app's behavior is consistent after your refactor.

This gap between TDD/BDD will lead a inference: 100% code coverage suggests you did very well in a TDD team, but it means nothing if you're in a BDD team. As the example shows, even you didn't write test for the validation, your test will cover it(you tests definitely will save a book object somewhere, thus emit the validation), but you won't know whether your books will still require a title after refactor.

2 comments:

  1. I don't think there are kinds of difference between TDD and BDD. Even in a TDD environment, the coverage is not the first priority, when you write a test first, what you wanna tot do is also trying to define the function behavior in different kinds of scenario. Since you didn't even have any code, you will not consider anything about the coverage in fact.

    ReplyDelete
  2. I think you're right. So what's the diff between TDD/BDD you think?

    Now BDD appears like a buzz word to me, while TDD looks like an revolution...

    ReplyDelete