Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unit testing philosophy

I have a "recipe" method which i am trying to write using TDD. It basically calls out to different methods and occasionally makes decisions based on results of these methods:

  public void HandleNewData(Data data)
  {
     var existingDataStore = dataProvider.Find(data.ID);
     if (data == null)
        return;

     UpdateDataStore(existingDataStore, data, CurrentDateTime);

     NotifyReceivedData(data);

     if (!dataValidator.Validate(data))
        return;

     //... more operations similar to above
  }

My knee jerk reaction would be to start writing test cases where I verify that HandleNewData calls the methods seen above passing the expected arguments and that it returns in those cases where the method call fails. But this feels to me kind of like this is a huge investment in time to code such a test up with little to no actual benefit.

So what is the real benefit of writing such a test? Or is it really not worth the bother?

It seems like it is just an over-specification of code it self, and will lead to maintenance problems whenever that code has to call another method or decide to not call one of the current methods anymore.

like image 926
dmg Avatar asked Apr 20 '26 11:04

dmg


1 Answers

TDD does not mean writing unit tests for code that already exists (although sometimes it may be necessary when improving legacy code).

You've probably heard the term "Red, Green, Refactor". This is the approach we take when doing TDD. Here are the three laws of Test-Driven Development, which take that a little further...

  1. You may not write production code until you have written a failing unit test.
  2. You may not write more of a unit test than is sufficient to fail, and not compiling is failing.
  3. You may not write more production code than is sufficient to pass the currently failing test.

The benefits of taking this approach is that you end up with very close to 100% unit-test coverage and you know that your code works exactly as specified.

It will reduce maintenance problems because as soon as somebody makes a change to your code and runs the tests, they will know if they have broken anything.

In this case, I would incrementally add unit tests for the methods being called from HandleNewData() before adding any for HandleNewData().

Adding unit tests to legacy code is tough, but doable and very much worth the effort. If you haven't yet, I really recommend reading Working Effectively with Legacy Code by Michael Feathers. I've found it invaluable when adding unit tests to a 25-year-old code-base.

like image 80
Johnsyweb Avatar answered Apr 24 '26 14:04

Johnsyweb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!