Posts

Showing posts from May, 2010

EJB3 unit testing - part two - replacing the initialcontext

Some of your code might use EJB session beans through JNDI lookup. To make this code find your session beans in your unit tests, you can replace the initial context quite easily. This is an example of how it can be done.


public class ReplaceInitialContext extends InitialContext implements InitialContextFactory {

static ReplaceInitialContext instance = null;

public ReplaceInitialContext() throws NamingException {
super(false);
}

public static ReplaceInitialContext getInstance() throws NamingException
{
if(instance == null)
{
System.setProperty("java.naming.factory.initial",ReplaceInitialContext.class.getName());
instance = new ReplaceInitialContext();
}
return instance;
}

@Override
protected void init(Hashtable environment) throws NamingException {
}

@Override
public Object lookup(String name) throws NamingException {
return "Hello";
}

public Context ge…