2010-11-20

JSF: Inject FacesContext

In JSF, the standard way of accessing FacesContext is through a static call:

FacesContext context =
   FacesContext.getCurrentInstance();

Static calls defy the purpose of OO programming, make unit testing hard, and you have to create a local variable.

Now, with the dawn of JEE6 and dependency injection you would like to do just that:

@Inject
private FacesContext facesContext;

But it doesn’t work. Here is some explanation why.


The solution


The solution is to use Seam Faces. Seam Faces allow you to access FacesContext, ExternalContext and NavigationHandler without having to make static calls.

Here’s how you can add it to your project:

<dependency>
   <groupId>org.jboss.seam.faces</groupId>
   <artifactId>seam-faces</artifactId>
   <version>3.0.0.Alpha3</version>
</dependency>

And it just works! Of course your server must support CDI.


Unit testing


Obviously, the tests require a bit of clumsy boilerplate. If you find it confusing, you can read more about unit testing with Arquillian.

package me.m1key.sample.singlecall;

import static org.junit.Assert.assertEquals;

import java.io.IOException;

import javax.inject.Inject;

import org.jboss.arquillian.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.impl.base.asset.ByteArrayAsset;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(Arquillian.class)
public class UserBeanTest {
   @Deployment
   public static JavaArchive createTestArchive()
           throws IllegalArgumentException, IOException {
       return ShrinkWrap.create("test.jar", JavaArchive.class)
               .addManifestResource(new ByteArrayAsset(new byte[0]),
                       ArchivePaths.create("beans.xml")).addClasses(
                       UserBean.class, MockFacesContext.class);
   }

   @Inject
   private UserBean userBean;

   @Test
   public void thereShouldBeTwoUserNames() {
       assertEquals(2, userBean.getUsernames().size());
   }

}


Sample


You can download sample code (a Maven app) that works on JBoss 6 M5.

1 comment:

  1. Or instead of including a entire framework you can include the following class:

    import javax.enterprise.context.RequestScoped;
    import javax.enterprise.inject.Produces;
    import javax.faces.context.FacesContext;

    public class FacesContextProducer {

    @Produces
    @RequestScoped
    public FacesContext getContext() {
    return FacesContext.getCurrentInstance();
    }
    }

    ReplyDelete