Saturday

Using CI to Test Code 4

Using CI to Test Code

Sometimes, the failure is due to a programming issue, which can be caught by a unit
test. You can have fun thinking up different parameters to test for.

Let's go back to our example of a function that performs a database query to delete a
record with a given ID from a given table. What does it do if:

• The ID is NULL, or '', or not set? (Particularly important this one, as you
might accidentally delete every entry in the table.)

• The ID is not an integer? ("x", for example?)

• The ID is an integer, but is out of range (you have 1000 entries in your table,
but this ID is 1001?)

• The ID is a negative number?

and so on. It's quite amusing thinking of different conditions to test for.

Throw them all at the function with a unit test, and see. However, think carefully
about the results you expect. The first case and second case are clearly programming
errors. You should rewrite your program to prevent this happening. So if it does, you
want the test to return failure.

We define the result we want from each test, so that we test if the program acted
correctly, not if the parameter is correct. If we submit an 'x', that's an incorrect
parameter; but if the program throws an exception, that is correct behavior. It helps
to write all the tests to show 'passed' if the program is doing what we want, so we
only have to take notice of exceptions.

The third case above, where the ID is an integer but out of range, is not necessarily
a programming error. The database should be able to sort this out safely. However,
what you need to do depends on your program and its objectives. Maybe, before you
submit the integer value, you need to check that it is within range? Or maybe you are
happy to let it run, in which case, because the program may return a database error
message to your screen, you need to intercept this and replace it with a bland 'sorry,
unable to do this at this time' error message? Or maybe test the delete operation for
success and branch accordingly?

Example of a Unit Test
Let's build some code to test the 'delete' function. I've set up a 'delete' function
(which is in a model) so that it detects that I am testing it, and on failure returns a
value ($dbvalue).