Testing Your Setup Code
By Adrian Sutton
In order to write atomic tests for classes I’ve gotten into the habit of injecting dependencies instead of creating them inside the class. This makes it simple to mock the dependencies but means that those dependencies are now externally visible instead of being neatly encapsulated and it means that somewhere in your code, there has to be a place that actually creates all these instances and passes them in.
I have no idea how to test that bit of code.
This pops up in a couple of places I’ve been working on lately, firstly the main method of a program. How do you atomically test a main method that by definition has to setup all the different objects and initialize everything. I suppose I could use a factory pattern but it seems like overkill. How are people testing these things?
The other problem area is in creating dialogs. I can separate out all the business logic and atomically test that, I can even use JFCUnit to test the GUI code for accessibility etc, but at some point my business code has to create the dialog and show it – how do I test that? I’d really like to keep my business code with 100% code coverage to avoid the slippery slope of just saying “oh I can’t test that” (which we’ve been sliding down a bit). I do need to make sure my atomic tests run really fast though.
Maybe I just have to live with no atomic tests for that bit of my code and leave the testing to integration tests but it opens up a whole in our TDD atomic test coverage which I’d like to avoid if I can.
Has anyone found a way to play with class loaders so that a call to new MyObject() actually creates a mock object/stub instead? Is that so ridiculously complex to do that you’d have no confidence in the resulting tests anyway?