Double benefit of unit testing

As soon as a programming project becomes a little more sophisticated, you will be confronted with the development of complex algorithms which requires intense testing and debugging. As this happened to me the last time a few weeks ago, I decided to write a short article about why I think, that unit testing is a perfect instrument for developing and debugging complex algorithms in a controlled environment and so it is more than just supporting regression tests during refactorings and enhancements of an app.

The app I’m currently developing allows to create multiple instances of a certain object, which is quite usual for a lot of apps 🙂
There are some main requirements to the object names:

  1. Default object names should recall somehow the type of the object the user has just created.
  2. Nevertheless object names should be unique.
  3. The user shouldn’t be constrained to interrupt his work entering a unique object name as new objects are created by touch in a graphical environment.

The object class therefore contains a property which proposes a readable name for the specific object which was just created by the user:

Clearly the proposed object name is not unique over every created object, so we need an additional method to uniqueing object names.

I wanted to apply a well known scheme for automatic naming of new objects which consists into appending an incremental numeric suffix to the given object name.

As the objects are stored into a core data managed object storage, we need to define a query, which retrieves objects from the store, whose names corresponds to the required naming scheme. The operation “beginswith” is just perfect for this purpose. We give the predicate our proposed name, the query checks for all entries which names starts with this proposed name.

The given method “findUniqueName” starts by obtaining a sorted list of all objects whose names corresponds to the naming convention “ObjectName” + [Numeric Suffix], where numeric suffix may be empty.
If no object was found at all, the name is already unique so the method just returns the name given in the parameter list.
For the performance and simplicity reasons, we just consider the last object in the list, which means that gaps in the enumeration of object names will not be filled by the lookup.
A regular expression is used to extract the numeric suffix from the name found in the database. If no numeric suffix is found, a “1” is appended to the given name and returned as the proposed unique name for the object. If a suffix is found, its numerical value is incremented. The suffix is replaced in the last name found in the list so we can be sure, that the new name is unique.

Of course we don’t consider concurrent database access which could produce duplicates during the execution of this method. Therefore other mechanisms should be applied to make sure, that duplicates are handled even in concurrent access situations.

There are a lot of cases where such a function may fail due to programming errors, since many different technologies and framework functionalities are applied here. We have database queries, regular expressions, string substitutions and last but not least a reasonably complex workflow that may be subject to a failure. In addition to the many possible error sources it would be interesting to test all the different execution paths in a controlled environment in order to find out if a programming error occurred.

Besides all the possible testing scenarios I personally prefer an environment, where I can do isolated tests and debugging without all the user interface stuff and without having to navigate to the function I want to test every time I recompile a new version. Here’s the point where unit testing comes to its double benefit: fast and easy testing during development and debugging and an automated regression test to be reused whenever something has changed. Some of you will know this as an element of “Test driven development”.

Now since we are using Xcode’s unit testing framework nearly everything is in place to support the development of unit test. The class we want to test is based on core data, so we have to prepare something to be able to interact with a managed object context. Here’s how we do it:

Xcode’s testing environment offers a standard setup method for preparing the individual tests of a test case. First we call the method of the super class, you never know… from the testing bundle (which also should refer to the managed object model of your app) the managed object model is extracted and assigned to the persistent store coordinator via its initializer. The persistent store required for the test execution is allocated and initialized along with a managed object context to perform all required database operations. Our objects are part of an object collection, which we also initialize during our setup phase. All the changes (here the insertion of the new collection) are saved to the managed object context via the “saveChanges” method. See the “saveChanges” in the following for completeness:

Now we can concentrate on the test method. In Xcode test methods are recognized automatically by naming them with the prefix “test” and having a void return type and no parameters. We provide a unit test, which checks the names of newly inserted objects for conformance to the previously discussed schema:

The test method tries to walk through all paths of the “findUniqueName” method checking if the created names are as expected. I used this method for debugging as well, without the need of repeatedly starting the app and navigating all the way to the function to test, which speeded up development significantly.

Xcode also offers a tear down method to clean up all the stuff that has been created and initialized during testing. Here it is used to clean up all created entities, just by deleting all the collections of objects from the database, this also covers other potential tests:

I personally use to write unit tests whenever a similar scenario appears or just before refactoring of an existing function, this is my way of doing test driven development in a very pragmatic way and just when it is really needed. It definitely helps me developing and refactoring robust code faster than just doing simple manual or automated application tests.