UI-Component Sets

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

Unit Testing

There are multiple strategies to deal with Unit Testing when you are using MyFaces, but over the time we have identified two possible alternatives.

  1. MyFaces Test: unit testing using predefined mock objects for JSF artifacts. See MyFaces Test Homepage
  2. MyFaces Core Test Impl Module (new feature since 2.2.1): run a full MyFaces Core instance inside a JUnit 4 Test using a runner or an already initialized base class. In this mode it is also possible to run JSF + CDI.

The recommended strategy when you are creating your own unit tests is first define the scenario to test and then identify the right tool for the job. Let's see when and how each option works.

Using MyFaces Test

If you are testing some methods in a JSF managed bean or a CDI bean, or if you need to check if a Validator or Converter works, possibly the only thing you need is a dummy FacesContext instance and an environment where the beans lives. In that case, MyFaces Test provide some base classes for your JUnit tests or if you need more flexibility it also has a class that encapsulates a mocked container. See org.apache.myfaces.test.mock.MockedJsfTestContainer for details. If you are using CDI, there are different options out there to run a CDI container inside a JUnit test that can be mixed with MyFaces Test.

See MyFaces Test Homepage for more information about how to use this library.

MyFaces Core Test Impl Module

If you need to validate some behavior that is bound to the JSF lifecycle, for example create a view like in a real request, input some values and click on a submit button, or check the view structure, or check the navigation algorithm, or check the interaction between your JSF views and your beans, then you need a JSF test environment that can be as close as possible to the real one in your web application running in a web server.

In this case, the interest resides on test a complex server side logic and forget about the client side, which is usually encapsulated by the JSF component. If you need a full simulation you are probably looking for functional testing, and in that case, tools like Arquillian, Selenium or Cargo + HtmlUnit can help you better.

MyFaces Core Test Impl Module helps you to run MyFaces Core inside a JUnit Test using a mocked servlet environment. The idea is "simulate" the effect of the rendered html markup and javascript using a MockMyFacesClient which manipulates a ServletMockContainer and add the necessary request parameters in the same way as a web browser sends an HTTP request and then the web container decodes. If you are using a third party JSF component library, it is easy to ceate a custom client class taking MockMyFacesClient as base model and checking how HTTP requests are filled by a real web browser.

Below you can find more information about how to use this library.