Forget to inject your dependancy in "application" code.
I've run across this problem at least 3 or 4 times since I've started to use JUnit (and therefore IoC).
Let's say I made this test:
public class ExampleTest extends TestCase {
public void testMyMethod() {
Example myExample = new Example();
myExample.setDataSource(mockDataSource);
boolean isOk = myExample.myMethod();
assertTrue(isOk);
}
}
Everything find,
green bar!
My application code (where it's really use):
Example myExample = new Example();
// oups! I did it again! forgot this line:
// myExample.setDataSource(realDataSource);
boolean isOk = myExample.myMethod();
I usualy get a
NullPointer, using stack trace one can easily find the problem but can I avoid it?
One way to avoid is to inject a default dehavior like this:
public class Exemple {
private DataSource dataSource;
public boolean myMethod() {
getDataSource().getConnection();
// ...
}
public DataSource getDataSource() {
if (dataSource == null) {
dataSource = new RealDataSource();
}
return dataSource;
}
}
I don't like this solution because using eclipse wizard to create getter/setter methods, I can (and I already have)
forget to modify the getDataSource like above and also I can
use directly the instance: dataSource.
An other solution could be to
assemble the different parts of the object in an
AssemblyObject of some kind and create a JUnit that assert that none of the attributes a null... but I'm not sure how to do this and still run my tests without the cointainer ?! (for exemple if RealDataSource use JNDI tree to locate dataSource)
Anyone already solved this problem?