Unit testing adds a new capability to application
development testing. The ability to execute code that ensures the design,
logic, and functionality of an application is the key to developing successful,
bug-free software. However, there are times where unit testing is not enough. This
is especially true when the properties/methods you really need to test are
declared private, protected, or internal/friend.
How do you compensate for that? Inheritance can work; for
instance, your unit test can inherit from the class that defines protected
methods, and validate these internal methods in that manner. That is useful,
but not always efficient. In addition, what about internal/friend and private
methods/properties?
Another option is reflection. Reflection has the
capabilities to peek underneath an object, inspect its metadata, and through
that get/set properties or invoke methods that you normally could not access.
This is one of the means we will look at.
Secondly, there is the concept of mocking/stubbing classes
in an application. Mocking is the art of inspecting an object's behavior to
ensure that it makes all of the correct assignments or operations. It even can
be used to test how the code handles if a different value is returned or if an
exception is thrown. Martin Fowler
calls this process "behavior verification," which is exactly what is
done with mocks.
From this, there are several ways to do this. The first that
I will show you is to create your own way to test the logic. I created a set
of components to do this in my Nucleo
Framework to test the logic. By inserting the logic you would like to
implement directly into a test, you can use these objects to mock the return
value. It is not illustrating the full value of mocking, as we shall see in
the following example using the TypeMock library, a freely-available library
that intercepts calls to your method and allows you to verify/control the
processing that goes on in a method. We shall see more examples below.