TDD – Add Exception Message
TDD – Add Exception Message
Our journey into TDD continues. Last time our tests drove us to create and throw a ZeroQuantity exception when we passed 0 as the quantity. All we want to do today is alter ZeroQuantity to contain an appropriate error message. Rather than create a new unit test, we’ll modify the existing test instead by adding a WithMessage() assertion:
Why don’t we write a new test? Shouldn’t each unit test do only one thing? Yes, that is true. What is one thing though?
The one thing is the testing scenario. In unit tests, we document how the system reacts to a given input. In our current case, it’s what happens when the input quantity is zero. Our error condition has not changed – we are only refining it with an exception message. Therefore the same test will do fine.
OK, what happens when we run the tests?
We get the expected behaviour – one test fails. No surprises here; ZeroQuantity is missing the new exception message:
The easy way to fix this is to hard-code the new error message. Is this acceptable? Sure, there isn’t anything that changes in our ZeroQuantity exception. The quantity is, and will always be, 0 for ZeroQuantity; it’s named for this condition. Let’s create a default constructor and call the base Exception class constructor passing in the fixed message:
Note that we entirely encapsulate the message in the exception. It’s a mistake to pass it in when one doesn’t need to. The exception type can ‘own’ its message.
Now the unit tests pass:
We’ve used TDD to drive ZeroQuantity exception to possess a message.
Leave a Reply
Want to join the discussion?Feel free to contribute!