Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should unit tests be written before the code is written?

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.

like image 559
Omar Kooheji Avatar asked Sep 05 '25 16:09

Omar Kooheji


1 Answers

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

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 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.

like image 134
Ben Scheirman Avatar answered Sep 07 '25 18:09

Ben Scheirman