To be honest I've not really seen much written detailing good (or even standard) ways of unit testing private methods without making their scope less restrictive than private. Thus I'll detail the way a co-worker a technique a co-worker and I came up with that seems like it will work pretty well. If you see any potential problems with this approach please just let me know in the comments.
The approach is fairly simple. We create a helper class that extends and "wraps" our class to be tested. This helper class then has simple methods in it that expose the private methods via a wrapper. So let's say we had a class, MoneyLender, with the private method of computeInterest(). Let's ignore whether that method should be private or not for arguments sake. We would create a MoneyLenderTestHelper class with a method in it called computerInterestWrapper() which actually just returns the private computeInterest method.
Right off the bat I have one potential concern and that is will the other private things (methods, member variables, etc) still be exposed to the private method that is being returned? I haven't tested this out yet so I don't know.
Anyway, my test would then instantiate the MoneyLenderTestHelper class, and call the computeInterestWrapper() method to get a reference to the private method to be tested. Then I could execute the method and perform the test. If the test needed to analyze the state of any private member variables I could create a helper method in MoneyLenderTestHelper that would inspect the private variable.
The main reason for returning a reference to the method in the helper class, instead of calling the helper method there, was so that I don't have to maintain the method signature in both the class being tested and in the helper class. My test obviously has to know the signature but overall this seems more maintainable.
What do you think? I'll post more as I muck around with the approach and let you know how well it all works. We've already implemented the idea on a few test cases but the private methods don't actually touch any private member variables; however, in the cases we have tried it with the technique has worked out well.
More Information visit ColdFusion Development Services.
Post a Comment