JSF: Inject FacesContext

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

FacesContext context =

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:

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:


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;

public class UserBeanTest {
   public static JavaArchive createTestArchive()
           throws IllegalArgumentException, IOException {
       return ShrinkWrap.create("test.jar", JavaArchive.class)
               .addManifestResource(new ByteArrayAsset(new byte[0]),
                       UserBean.class, MockFacesContext.class);

   private UserBean userBean;

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



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 {

    public FacesContext getContext() {
    return FacesContext.getCurrentInstance();