Start with a Unit Test

Not everyone is a fan of test-driven development.

Writing unit tests for your code can be a laborious task, and it has no immediate benefit to your customers.  So why waste any time writing the tests, right?

This past week, a colleague of mine summed up the problem pretty well:

I’ve finished writing the code for that feature.  Now I just need to take some time to sit down and write some unit tests for it.

Unit Test Results in Visual Studio

He’s not following test-driven development.  Instead, his tests come in as an afterthought.  Actually, most of us code this way.

We write a chunk of code to perform a task.  Then a customer asks for a new feature, so we write some more code.  Then a new hire comes in to the company demanding we take some time to go back and document our existing code base with unit tests.

It’s not fun. It’s not glamorous.  It feels like a waste of time.

But I still feel it’s the way things should be done. [Read more…]

Dependency Injection and Abstract Interfaces in C#

If you’ve ever written code, you’ve probably written a unit test.  If you haven’t written unit tests, you should start.



Unit tests let you quickly verify that your code is operating in a predictable fashion.  When you make changes down the road, you re-run the same unit tests to make sure nothing broke.

In many cases, you write the unit tests first.  Define what your code will do, decide what objects you will use/make to accomplish that, then write a test.  At this stage, the test will fail – but you have a place to start.  Now write your code until it passes the test and you can be certain your code, however inelegant it might be, is doing what you expect.

Sometimes, though, you don’t write the unit tests first.  You go back days, weeks, even years later and try to add unit tests to your code.  In most cases, this will be next to impossible because of the way the code is written.  A function with direct calls to the database needs to be rewritten.  File access needs to be abstracted into an object.

It’s tricky, but makes your code more maintainable in the long run.
[Read more…]