I can’t take credit for this approach, and even if I could, I probably wouldn’t, because it makes me feel kind of icky.
Anyway, I recently heard about a legacy code testing strategy where you mark your class as “partial”, and in another file, you add whatever public properties/methods you need for your tests. You make the contents of the second (testable file) conditionally compiled (the classic #IF DEBUG) so the encapsulation is still there for any release builds.
It’s kind of like endo-testing, but you’re extending the class “sideways” instead of “downwards”.
Basically, it’s breaking encapsulation in a controlled way, and for the most part, I think it’s a bad idea if you’re working with a new design. If, however, you’re trying to get some meaningful coverage for your legacy code (which wasn’t designed for testability) it can be a good stop-gap in dealing with the legacy code refactoring catch-22: where you don’t want to make changes without tests, but you can’t make tests without making changes.
Any strategy, such as this one, which allows you to get the first layer of tests down before further refactoring, should be embraced as a good thing. If you find that you need to do this for any new/original classes, my guess is that your class is too big and needs to be decomposed further into more cohesive and testable classes.
Although you’re not to credit, I thank you for bringing this to my attention. A colleague and I were discussing the exact same problem yesterday, and this is the best solution I’ve seen so far.