Unit-testing – Do you really have to do BDD/TDD in a test first manner

tddunit testing

Even though I haven't been in a TDD or BDD project, or I have been in some that say they are doing TDD but are pretty far from it, these are things that I think about and really try to read as much as I can about.

Back to the question. When you're doing BDD you should write your "test" first and make it fail, right? And then implement that feature or what you call it. But if you take this to the extreme couldn't this be some kind of top-down development? You're looking at your UI and says, "I would like to have this feature/behavior here". Then you fix your UI to implement that feature and the code that supports the UI. At this point you haven't implemented any business logic or data access logic, you have just implemented your behavior. What I'm aiming at instead of writing the test first you write your UI code first. In some cases it should result in the same code for the data access and business layer, since you use your UI code to define what your business needs to support.

Of course you should complement this with tests that is used to make sure that the feature is working as it should in the feature.

Any thoughts?

Best Answer

You are talking about BDD from a high level perspective of testing your UI. Testing is a bit more fluffy at this level than lower down in your Javascript/server side code.

Several books I've read on TDD say you should write code as if the underlying systems exist, and just write enough to get your test to pass. You can write stubs on the server to get your UI behavioural tests pass. Then you start at this stub seam and write some unit tests for your server side code and work your way down to a full implementation.

I often code as if underlying layers exist to get a high level test to pass, it does feel like going down a rabbit hole and extracting many other classes to satisfy the high level test, and then writing tests for these lower levels. As you've already recognised, it helps to keep you focused starting with higher level tests.

As any seasoned programmer knows, there are many layers to software development. I tend to work lower than the UI and think about the data or behaviour my UI needs from the server and start there (maybe because I don't do much UI work these days).

If I'm really honest, extracting a class from the underlying layers means I'm not doing test first but ... within minutes or sometimes hours I'll have a test for that code. This still feel beneficial to me as I helps see where you might need to supply dependencies to a class and honour the single responsibility principle - if it's hard to test, you're doing too much in one place etc.