UI-Component Sets

Home » Wiki » MyFaces Core » MyFaces Core User Guide » JSF and MyFaces Howtos » Unit Testing

Create Test from Base Class

First create a test class that extends from:

  • org.apache.myfaces.mc.test.core.AbstractMyFacesRequestTestCase
  • org.apache.myfaces.mc.test.core.AbstractMyFacesCDIRequestTestCase (Use Apache OpenWebbeans)

For example

public class SimpleTestCase extends AbstractMyFacesCDIRequestTestCase
{
    @Inject
    @Named("helloWorld")
    private HelloWorldController helloWorldBean;

    @Test
    public void testHelloWorld() throws Exception
    {
        startViewRequest("/helloWorld.xhtml");
        processLifecycleExecute();
        Assert.assertEquals("page2.xhtml", helloWorldBean.send());
        renderResponse();

        client.inputText("mainForm:name", "John Smith");
        // The button end current request and start a new request 
        // with a simulated submit 
        client.submit("mainForm:submit");

        processLifecycleExecute();
        Assert.assertEquals("John Smith", helloWorldBean.getName());
        Assert.assertEquals("/page2.xhtml", facesContext.getViewRoot().getViewId());
        endRequest();
    }

    @Override
    protected ExpressionFactory createExpressionFactory()
    {
        return new com.sun.el.ExpressionFactoryImpl();
    }

    @Override
    protected String getWebappResourcePath()
    {
        return "webapp";
    }
}

The method getWebappResourcePath() defines where in the test classpath are the pages to load. createExpressionFactory() defines the EL Expression factory used. There are many examples available in MyFaces Core 2.2.x impl module, so just take a look and the code.