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 getInitialContext(Hashtable environment) throws NamingException {
return getInstance();
}

public static void main(String[] args) throws NamingException
{
ReplaceInitialContext.getInstance();
System.out.println(new InitialContext().lookup("test")+"");
}
}

Comments

Popular posts from this blog

My VNC based development environment with Visual Studio Code running on Ubuntu

Intercepting and adjusting SQL generated by Eclipselink JPA

Exporting Kendo UI GRID to Excel with Java