Avi
Avi

Reputation: 16176

Unit testing - should I test argument validation code

I always validate arguments. I'm just starting with unit testing. Should I add tests that verify that exceptions are raised for invalid arguments?

For example, suppose an integer argument should be in the range 3..5. Then I have a validation that throws an out-of-range exception if it's below 3 or above 5, but now I'd have to write additional two-and-a-bit test cases - two that verify that exceptions are thrown with values below 3 and about 5, and one test case that verifies that when all arguments are valid no exception is thrown.

I'm torn - "devil and angle on my shoulders" situation :). The "nobody got fired for choosing I.B.M." logic says: "Someone WILL pass an invalid argument. You've invested effort to verify that this is handled by validating the arguments. Go the extra mile and invest in a few tests cases for each argument to verify that your argument validation is working."

But the down-to-earth logic says - "This is dead weight. The validation code itself is just insurance. Adding test cases on the validation is a waste of money, adding another layer of insurance".

What should I do?

So, my question is: "Should I, for each argument of every public method, write test-cases to verify that argument validating code indeed works?"

Upvotes: 2

Views: 1156

Answers (1)

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44449

Yes, you should. This is exactly the kind of scenario perfectly fit for unit-testing: a small operation with a few possible inputs.

To say that you have to do this for each argument though is different: only do it for those that have some logic performed onto them.

Ideally, you want each requirement reflected in a test: "if a string is null, throw an argumentexception" should have a corresponding unit test.

I agree that these tests are trivial to write but they will give you a lot of reassurance the basics of your code do what they are supposed to do. They will also be very quick to write, certainly if you just copy it around and change a few values where needed.

Validation code is insurance but it's an essential part of insurance: if the validation doesn't work, your program enters unspecified territory. Make sure the insurance works.

Upvotes: 5

Related Questions