User DocumentationOne minute descriptionTwo minute tutorial Five minute introduction Advanced Topics FAQ Container Components Terminology Mock Objects Inversion of Control Types PatternsInversion of ControlDependency Injection Constructor Injection Setter Injection Interface-Impl Separation Lifecycle Antipatterns Developer DocumentationHow To ContributeRelative Volunteering Release Process Project InformationSloganMailing lists Source Repositories Open Issues Blog entries Statistics Team Sister Projects TShirts MiscellaneousDifferentiatorsNirvana Full Sitemap |
Mock ObjectsIf you have it up to here with codebases that drag along everything and the kitchen sink, (possibly using the Singleton antipattern) you must read this page. Classes that look up or instantiate heavyweight classes themselves are such beasts. As you might have experienced, they are a pain to test. (And ample proof that the authors didn't follow TDD This illustration shows how:
The classHere is what NeedsStuff might look like:public class NeedsStuff { // These are both interfaces. private final BlueStuff bs; private final GreenStuff gs; public NeedsStuff(BlueStuff bs, GreenStuff gs) { this.bs = bs; this.gs = gs; } public String doIt() { return bs.jump() + gs.beatIt(); } } During test time we'll give NeedsStuff some mocks. During prime time (when the final application is running), the NeedsStuff class will be instantiated with a SuperHeavyBlueStuff and a NuclearGreenStuff instance. These require some really heavy infrastructure such as database connections and network access. We don't want to drag along that when we test NeedsStuff! (It can wait till the integration test). Test TimeOur test becomes like this: public class NeedsStuffTestCase extends junit.framework.TestCase { public void testNeedsStuffDoesStuff() { BlueStuff bs = createBlueStuffMockThatReturnsBlahOnJump(); GreenStuff gs = createGreanStuffMockThatReturnsHuhOnBeatIt(); NeedsStuff ns = new NeedsStuff(bs, gs); assertEquals("BlahHuh", ns.doIt()); // verify mocks. } } We are testing the doIt() method without having to drag along any heavy dependencies ![]() ![]() Prime TimeIt is left to PicoContainer to instantiate NeedsStuff. In order for it to succeed, we must also configure the container with some real BlueStuff and GreanStuff:public class AppBootstrapper { public void runapp() { MutablePicoContainer pico = new DefaultPicoContainer(); pico.registerComponentImplementation(NeedsStuff.class); pico.registerComponentImplementation(SuperHeavyBlueStuff.class); pico.registerComponentImplementation(NuclearGreenStuff.class); } }
|