Unit Testing – Should Unit Test Input Values Be Validated?

unit testing

I am manually creating a rather large data model as input to my unit tests. Data model is created using a number of builders. Developers use these builders in order to create the data model as they see fit for a particular unit test.

An example might be in order: when reporting work time, it is possible to report taking a break. This break must be within the working hours, no sense in taking a break at midnight if you worked a 9am-5pm shift.

I have kept from validating any of the inputs into the builders, because:

  • I believe developers should be familiar with data they create.
  • Makes the builders more complex. Testing infrastructure should be as simple as possible, in my opinion.

Of course, this means the developer can make a mistake and create a break that is outside of the working hours.

A colleague of mine proposed I do some validation, e.g. making sure the break falls into the working day. It is a minor change and introducing it won't complicate things, but it got me thinking.

Is it a smart move to validate input data for your unit tests, and what are the drawbacks here?

Best Answer

Unit tests don't always have valid input data - invalid data is a very common input for unit tests, in fact, to make sure it is handled properly. Presumably these data models are used in your production code as well, and your production code knows what to do with invalid data (e.g., a break at midnight). Thus, there is no need for the unit test to validate the data model, as that should be handled by the code under test - that could be the very point of the unit test, in fact.

If your production code doesn't use these same data models, I'd be wary of using them in your unit tests. Another piece of untested code introduces possible bugs in your unit tests, potentially leading to false positive test results.

Related Topic