Oh ok, not that kind of mocking. But seriously if you are doing this in a spring bean:
@Resource
private String rootURL
Then you can use Spring to define a a bean to fill it in, then all is well. But what if you are doing:
@Resource(mappedName="rootURL")
private String rootURL
Well then you are most likely using something like a deployment descriptor (e.g. web.xml) to define the environment variable e.g.
<env-entry>
<description>Root URL for a blog</description>
<env-entry-name>rootURL</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>http://www.blogger.com</env-entry-value>
</env-entry>
But what happens when you try to use JUnit, probably nothing bad, but what if you are using Spring to run your JUnit? Then you will most likely get this kind of error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'blogDAO':
Injection of resource fields failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'rootURL' defined in JNDI environment:
JNDI lookup failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
This is down there not being the JNDI eniroment you were expecting, so how can you mock one up? Buy adding this to your JUnit test:
public static void buildJndi() {
try {
SimpleNamingContextBuilder builder = SimpleNamingContextBuilder.emptyActivatedContextBuilder();
String rootURL = "http://www.blogger.com";
builder.bind("rootURL", rootURL);
} catch (NamingException e) {
}
}
and calling it in the unit tests constructor.
For more information checkout:
http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/mock/jndi/SimpleNamingContextBuilder.html