ResinBeanContainer: embedding CDI for testing
Since unit testing and test-driven development have become accepted as the basis for solid programming practices, we’ve had several requests to provide a lightweight Resin environment specifically tailored to test environments. As our first cut, we’ve created a ResinBeanContainer class, usable outside of Resin, but providing a Resin environment.
The ResinBeanConstainer provides the same environment as a Resin web-app, but without the servlets, HTTP or requests. It provides CDI injection, EJB lite support, database and JPA configuration.
Like Resin, the ResinBeanContainer scans the classpath for CDI beans.xml and EJB ejb-jar.xml files and populates the container with the found beans.
import com.caucho.resin.ResinBeanContainer;
class MyTestClass {
public void myTest()
{
ResinBeanContainer beans = new ResinBeanContainer();
beans.start();
RequestContext request = beans.startRequest();
try {
MyBean bean = beans.getInstance(MyBean.class);
bean.doStuff();
} finally {
request.close();
}
beans.close();
}
The ResinBeansContainer.start() call initializes the container, telling it to scan the classpath, and instantiate and start @Startup beans.
The ResinBeansContainer.startRequest() creates a new CDI @RequestScoped context for the current thread. The thread is now inside CDI and inside the container, basically running as if you were in a live Resin instance.
The ResinBeansContainer.getInstance(MyBean.class) creates a CDI-injected instance of the MyBean class. Assuming MyBean has @Inject methods, you’ll see the populated values.
And finally, the close() methods complete the request and close the ResinBeansContainer context. It’s critical to close both the request context and the container, to make sure they are properly garbage collected.
