I've said that you can't do unit testing without units. Sounds funny or trite, but is very true. If you are doing Test Driven Development (TDD) and develop the unit in concert with the tests then the unit is built to be testable. Existing software is a very different thing.
Units are usually classes. It is also possible to treat individual programs as units. If you are working in a language like Visual FoxPro a PRG or a collection of functions in a PRG can be units. The definition of a unit that I'll use here is a single class or function that can be isolated. If the unit can't be isolated then you are essentially doing integration or maybe even system testing. Existing software that instances classes, accesses the database or other types of external access is very hard to isolate.
Unit testing should occur when the unit can be fully isolated and all aspects of it's existence and execution can be controlled by the test environment. Ideally the setup and teardown of the test should fully provide all the preconditions and things the unit needs to access. When testing existing software this is harder to accomplish. If the unit accesses the database and processes the data and both returns a result and has side-effects of modifying the database, that unit becomes much harder to isolate and test. To truly isolate it, a fake or copy database would have to be used. Assertions would have to be written to verify the output and the modifications done to the database.
Mock objects can be used to test a unit. A mock object is just an object that fakes the tested unit into thinking that it is the real object that the unit should interact with during it's execution. A mock database would be just enough database to provide the tables and fields that the unit would expect or it could be a copy of the full database with just enough filled in to provide the unit with what it needs.
In theory, you should be able to build enough mock entities to isolate most existing units. The problem is that it takes a lot of work to mock some items. To mock classes that the unit instances you can change the search path or change the loaded environments. In Visual FoxPro you can SET PROCEDURE or SET CLASSLIB to a different path where mocked objects live. An Active-X object could actually be mocked by installing a mock version in place of the real one. This would probably require a test system where only the testing was done and no real execution took place. Databases can be copied or faked. External systems like SQL Server can be faked or re-directed to a copy just for testing. The problem is cost. Some of these operations would take many hours to setup. Thus cost might help decide which existing units can be practically unit tested or will just have to continue to be tested the old fashioned way.
Recent Comments