[Tutor] More on unit testing - tests for external data...

Alan Gauld alan.gauld at btinternet.com
Thu Dec 10 01:15:35 CET 2009

"Modulok" <modulok at gmail.com> wrote

> Unit testing functions and methods which rely on passed data is simple
> enough. However:
> How do I unit test something which relies on external data?

You have to build a test environment.
This needs to be carefully planned to enable every test condition 
to be tested.

> For example, a function which creates a file only if it doesn't exist
> on disk, or a unit test for a function which makes an SQL query? 

So you would need a file that exists, one that doesn't(!), 
one that exists but is read-only, one that exists but wrong user 
ownership, and really a binary file and a text file and an 
empty file and a huge file too

For the database it gets tricky, you need to create a database 
full of entries with all the possible scenarios you might encounter.
For a large application with multiple joined tables designing such 
a test database can take a lot of time - but it is invaluable for testing 
and debugging and provided you store a clean copy somewhere 
before using it makes regression testing possible.
Once you have the database you then need to write the test driver 
code that will provide the right keys for each test - database testing 
is one of the biggest challenges in system testing.

And don't forget to test for behaviour with invalid user access on 
the database, and for locking and simultaneous updates etc.
And if its on a separate server that you check behaviour when 
the server or network is down or running slowly (eg by lowering 
server priorioty and running a huge bulk update in the background).

Remember, in testing you are not trying to prove it works but rather 
to demonstrate that it doesn't!

Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list