C# Unit Testing – How to Test Methods with Only Guard Clauses

cunit testing

Say I have a method like this:

public void OrderNewWidget(Widget widget)
{
   if ((widget.PartNumber > 0) && (widget.PartAvailable))
   {
        WigdetOrderingService.OrderNewWidgetAsync(widget.PartNumber);
   }
}

I have several such methods in my code (the front half to an async Web Service call).

I am debating if it is useful to get them covered with unit tests. Yes there is logic here, but it is only guard logic. (Meaning I make sure I have the stuff I need before I allow the web service call to happen.)

Part of me says "sure you can unit test them, but it is not worth the time" (I am on a project that is already behind schedule).

But the other side of me says, if you don't unit test them, and someone changes the Guards, then there could be problems.

But the first part of me says back, if someone changes the guards, then you are just making more work for them (because now they have to change the guards and the unit tests for the guards).

For example, if my service assumes responsibility to check for Widget availability then I may not want that guard any more. If it is under unit test, I have to change two places now.

I see pros and cons in both ways. So I thought I would ask what others have done.

Best Answer

Part of me says "sure you can unit test them, but it is not worth the time" (I am on a project that is already behind schedule).

It's three very short tests. You spent as much time asking yourself the question.

But the other side of me says, if you don't unit test them, and someone changes the Guards, then there could be problems.

Listen to this side.

But the first part of me says back, if someone changes the guards, then you are just making more work for them (because now they have to change the guards and the unit tests for the guards).

If your maintainer is a TDD nut, you're making it more difficult for them. Any change I make without there being a related change or addition of tests leads to my having to think hard. In fact, I would probably add the tests before I go ahead and make the change.

The first part of you is just plain wrong. Give the second part a pat on the back and stop thinking about it.

Related Topic