Unit-testing Java Server Faces backing beans

Thursday, 29 December 2011 22:37 GMT | Add a comment

Here’s a quick tip for testing JSF backing beans. If you need to run a unit-test for a bean that contains a validate(…) throws ValidatorException method, you may come across the following error message.

Absent Code attribute in method that is not native or abstract in class file javax/faces/validator/ValidatorException

From my cursory research, it appears that the test-runner expects actual implementations of ValidatorException, whereas your compiled tests only have access to the API [interfaces]. Many search results point to solutions along the line of “use an alternative JavaEE API that includes the implementation, e.g. Geronimo”.

However, my personal opinion is that basing the correctness of your code on specific implementations can do more harm than good, and that a better solution is to design your classes so that the code that actually needs testing is isolated into an abstract class.

For example, say I have an

<f:viewParam id=”id” name=”id” value=”#{actionDetailsBean.id}”>

with a validator bound to method #{actionDetailsBean.validate}.

The proper way  of implementing this is to completely move the validation code away from JSF, such that you end up with a delegate method that gets called by the bound validate(…) method.

The following code snippet shows how the validation method would be called.

@ManagedBean(name="actionDetailsBean")
@RequestScoped
public class ActionDetailsBean extends AbstractActionDetailsBean {

    private static final String COMPONENT_ID = "id";

    public ActionDetailsBean() {
        super();
    }

    public ActionDetailsBean(ActionDetailsBeanOut actionDetailsBeanOut) {
        super(actionDetailsBeanOut);
    }

    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException{
        switch (component.getId().toLowerCase()) {
            case COMPONENT_ID:
                validateId();
                break;
        }
    }

    private void validateId() {
        load();
        if (!isLoaded())
            throw new ValidatorException(new FacesMessage("Id not recognised."));
    }
}

In this example, validateId() is an extracted method that calls the load() method. The isLoaded() method returns a boolean to indicate whether the “action details” were loaded and, by extension, whether the id was valid.

Another principle of unit-testing is that methods should be tested for their ability to fulfil their responsibility without much concern to how they are implemented. In this case, there is no point of testing the validate(…) and validateId() methods. We should trust that validate(…) will get called by JSF and will throw a ValidatorException if there is a validation error, implying that testing of the load() method should be sufficient.

The following snippet shows the superclass for ActionDetailsBean.

public abstract class AbstractActionDetailsBean {

    @Inject
    protected ActionDetailsBeanOut actionDetailsBeanOut;

    private String id;
    private String title;
    private String description;
    private String context;
    private boolean loaded;

    public AbstractActionDetailsBean() {
    }

    public AbstractActionDetailsBean(ActionDetailsBeanOut actionDetailsBeanOut) {
        this.actionDetailsBeanOut = actionDetailsBeanOut;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getContext() {
        return context;
    }

    public void setContext(String context) {
        this.context = context;
    }

    protected boolean isLoaded() {
        return loaded;
    }

    public void load() {
        if (loaded) return;
        Map actionDetails = actionDetailsBeanOut.requestActionDetails(id);
        if (null == actionDetails) return;
        setId((String) actionDetails.get("id"));
        setTitle((String) actionDetails.get("title"));
        setDescription((String) actionDetails.get("description"));
        setContext((String) actionDetails.get("context"));
        loaded = true;
    }
}

Here, ActionDetailsBeanOut is an SPI interface, the implementation of which is injected at run-time to provide “action data”. load() populates the bean and sets loaded to true, if successful. AbstractActionDetailsBean has no dependency other than the injection.

Finally, coming back to the initial premise of this post, the way to avoid the dependency on a concrete JavaEE class and make your unit-test runnable is to test an anonymous implementation of AbstractActionDetailsBean, as follows.

public class AbstractActionDetailsBeanTest {

    @Test
    public void testLoad() {
        ActionDetailsBeanOut actionDetailsBeanOut = new ActionDetailsBeanOut() {
            @Override
            public Map requestActionDetails(String id) {
                HashMap details = new HashMap<>();
                details.put("id", "id");
                details.put("title", "title");
                details.put("description", "description");
                details.put("context", "@context");
                return details;
            }
        };
        AbstractActionDetailsBean actionDetailsBean = new AbstractActionDetailsBean(actionDetailsBeanOut) {};
        actionDetailsBean.setId("id");
        actionDetailsBean.load();
        Assert.assertEquals("id", actionDetailsBean.getId());
        Assert.assertEquals("title", actionDetailsBean.getTitle());
        Assert.assertEquals("description", actionDetailsBean.getDescription());
        Assert.assertEquals("@context", actionDetailsBean.getContext());
        Assert.assertTrue(actionDetailsBean.isLoaded());
    }
}

No Comments yet

RSS feed for comments on this post. TrackBack URI

Leave a comment

XHTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>



Powered by WordPress and Eddy Young.

DISCLAIMER: This site is supported by advertising. As a result, cookies may be installed by advertisers in order to track usage and trends. If you do not want this, please disable cookies for this site.