I'm having trouble developing unit testing approaches to testing both if the "code does what I want it to do", and testing "does my code work".
For example, I'm writing code to validate input that will be inserted into a database table, so I need to test if my code does what I want it to do - Good input is accepted, bad input is rejected. Here's some of the code, in VB.NET:
'Let's check if we are going to update all the fields that must be updated...
If record.table.RequiredMustBeSuplied IsNot Nothing Then
For Each req In record.table.RequiredMustBeSuplied
If query.UpdateFields(req.Key).value Is Nothing Then
Throw New ArgumentNullException
End If
Next
End If
So, for my unit test I would pass in a query without the proper update fields and expect that it would result in a ArgumentNullException, and a corresponding test that passes. The problem that happens to me is later on I'll notice a bug, and realize my code doesn't work correctly. For example, the correct code in this case was:
'Let's check if we are going to update all the fields that must be updated...
If record.table.RequiredMustBeSuplied IsNot Nothing Then
For Each req In record.table.RequiredMustBeSuplied
If query.UpdateFields(req.Key).value Is Nothing Then
Throw New ArgumentNullException
End If
Next
End If
So, I was able to test for problems I know about (missing fields) but not a problem I don't know about (the difference between dbnull and nothing). Is unit testing just not very good at finding these kinds of errors, or is there an approach someone could suggest?
RequiredMustBeSupliednever beNothing, but an empty enumeration instead. This makes theIfredundant and hence the code cleaner. Using empty collections instead of null values is a good practice to follow, advised by many good books (e.g. Effective Java by Josh Bloch).