Posts

Showing posts from January, 2010

EJB3 unit testing - part one - dependency injection

You might want to use an embeddable container for this - but why really - cause it's really simple. EJB3 session beans are POJO's and should be tested like POJO's.

However there are some issues in order to get EJB3 unit tests working. One of them are dependency injection.

How does dependency injection work? Take a look at this method using reflection:


/**
* @param targetBean - the bean to inject into
* @param annotationClass - the annotation class representing the injection
* @param objectToInject - the object to inject into targetBean
*/

private void inject(Object targetBean, Class annotationClass, Object objectToInject)
{
// Scan all (private and public fields) of the bean class
for(Field fld : targetBean.getClass().getDeclaredFields())
{
// See if the specified annotation is present for the field
if(fld.isAnnotationPresent(annotationClass))
{
// See if the field type is appropriate according to the object that is to be injected
if(fld.getType().isAssi…