From: Ilja P. <pr...@di...> - 2004-02-05 12:35:34
|
moc...@li... wrote: > Subject: [MO-java-users] Making Mock Objects for Static Members > > > Hi, > > I have a class that I want to test but I'm having trouble > creating MockObjects for the classes referenced by my class. Consider > the code below: > > public class MyClassToTest > { > private ClassA a = ClassAFactory().instance().getGlobalClassA() > > public MyClassToTest() > { } > > public myMethodToTest() > { > ClassB classBInst = new ClassB(); > } > } > > I want to mock ClassA and ClassB. ClassA internally accesses > a database and ClassB makes a JNDI lookup and both classes > read configuration info from a properties file. Actually most > of my classes read config from properties files using something like: > private static final Properties PROPERTIES = > PropertiesLoader.load(PROPERTIES_FILE_NAME); > This is another thing that I want to mock. > > But how do I get the Mocks for ClassA and ClassB to > MyClassToTest? The only way to do it seems to me to pass > instances of ClassA and ClassB to the class constructor and > to the method as parameters. But this changes the public > interface of my class and I don't want the clients of this > class to be burdened with the details of creating ClassA and > ClassB. So how can I effectively test MyClassToTest? For ClassA, you could make the ClassAFactory configurable. The test would configure it so that instance() returns a mock implementation. (That's what factories are for, aren't they???) For ClassB, you could enhance the interface by a myMethodToTest(ClassB), and the method without the parameter could simly delegate to it (so that it's dumb enough to not need testing at all). Does that help? |