<img height="1" width="1" style="display:none;" alt="" src="https://px.ads.linkedin.com/collect/?pid=299788&amp;fmt=gif">

Unit Testing Spring MVC Portlets

Software Development, Portal, Software Solutions, Java

By Robert Hall

Unit testing has long been considered a critical part of the development cycle for Java developers, especially those practicing test-driven development or Agile methodologies. This should be no different when using a portlet framework such as Spring Portlet MVC.  This post will discuss a few examples of writing unit tests for testing various Spring Portlet MVC components.

Context Loader Mocking

Consider a portlet with one or more MVC Controller objects. Using Spring MVC removes your dependency on a servlet container. You should be able to test your controllers, and your entire web stack, from a testing harness like JUnit. However, by using Spring you become dependent on services provided by DispatcherServlet and a complete WebApplicationContext which includes request parameter binding, validation, model attributes, request mappings, and aspects such as Spring Security. The initial step to unit testing with Spring MVC is to create a mock servlet context and WebApplicationContext from within JUnit. Create a custom mock ContextLoader to set up the Portlet environment. We create MockPortletContext and MockPortletConfig objects using our MockWebApplication for configuration. Then we create an instance of DispatcherPortlet and configure it. Notice the use of a MockViewResolver:

final ViewResolver viewResolver = new MockViewResolver();
portletApplicationContext.addBeanFactoryPostProcessor(new BeanFactoryPostProcesor() {
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
beanFactory.registerResolvableDependency(DispatcherPortlet.class, dispatcherPortlet);
beanFactory.registerResolvableDependency(ViewResolver.class, viewResolver);
This ViewResolver implementation stores a view name and model, so we can check them later on for testing purposes.  This means we can ignore whatever view technology we are using for the tests.  The ContextLoader will be given the opportunity to load an application context and create a servlet environment for the tests before they are run.


Controller Testing

Consider a simple controller example derived from a recent client portlet project I worked on.

public class UserAccountController {
private UserAccountService userAccountService;
public UserAccountController(@Qualifier(“userAccountService”) UserAccountService userAccountService) {
this.userAccountService = userAccountService;
along with its autowired service
public class UserAccountServiceImpl extends ApplicationObjectSupport implements UserAccountService {
To test this controller I created a JUnit class and injected the DispatcherPortlet and ViewResolver from the application context. Note the use of the test application context in the configuration.
public class UserAccountsControllerIntegrationTest {
private DispatcherPortlet dispatcherPortlet;
private MockViewResolver viewResolver;
private UserAccountService userAccountService;
Since the UserAccountsController has listed @SessionAttributes, we need to add a UserAccount attribute to the portlet session for each request:
private void setupRequestSession(PortletRequest request) {
UserAccount userAccount = new UserAccount(username,accountNumber, accountType);
PortletUtils.setSessionAttribute(request, “userAccount”, userAccount);
This then allows us to set some expected parameters, call dispatcherPortlet.render(request, response) or dispatcherPortlet.processAction(request, response), and ensure the correct action or render method gets called. Testing Render Methods In this example, there are four render methods in the controller under test; setting no extra parameters in the render request should call the viewListOfUserAccounts method. We can test this as follows:
public void viewListOfUserAccounts() throws ServletException, IOException, PortletException {
MockRenderRequest request = new MockRenderRequest();
dispatcherPortlet.render(request, new MockRenderResponse());
If we want to trigger a different render method, some parameters will need adding to the request.  We can use addParameter() on MockRenderRequest:
public void viewUserAccount() throws ServletException, IOException, PortletException {
final Integer TEST_ID = 2;
MockRenderRequest request = new MockRenderRequest();
request.addParameter(“userAccount”, TEST_ID.toString());
request.addParameter(“action”, “viewUserAccount”);
dispatcherPortlet.render(request, new MockRenderResponse());
With render methods, the first thing to check is that we get the expected view name returned.The DispatcherPortlet itself will usually handle this, but for test purposes we can utilize our MockViewResolver:
assertEquals(“Unexpected view name found”, “userAccounts”, viewResolver.getViewName());
We may also want to check what gets added to the Spring Model; this will be stored as a request attribute under ViewRendererServlet.MODEL_ATTRIBUTE, so we can check that expected values have been added:
assertNotNull(“No UI model found”, request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE));
ModelMap model = (ModelMap) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE);
assertNotNull(“Null list of userAccounts found in model”, model.get(“userAccounts”));
assertTrue(“List of userAccounts found in model was not a Sorted Set”, model.get(“userAccounts”) instanceof SortedSet);
SortedSet modelUserAccounts = (SortedSet) model.get(“userAccounts”);
assertEquals(“Incorrect number of userAccounts found in model”,
userAccountService.getAllUserAccounts().size(), modelUserAccounts.size());

Testing Action Methods

Action methods generally require more request parameters to be added. For instance, the deleteUserAccount method

@RequestMapping(params = “action=deleteUserAccount”)
public void deleteUserAccount(ActionResponse response, @RequestParam(“userAccount”) Integer id) {
will need request parameters
request.addParameter(“action”, “deleteUserAccount”);
request.addParameter(“userAccount”, “2″);
There can also be action methods with formal parameters annotated as @ModelAttribute, such as submitAddUserAccountFormPage:
@RequestMapping(params = “action=addUserAccount”)
public void submitAddUserAccountFormPage(ActionRequest request, ActionResponse response, @ModelAttribute(“userAccount”) UserAccount userAccount,
BindingResult result, @RequestParam(“_page”) int currentPage, Model model) {
In this case we’ve already covered the “userAccount” parameter, adding it as a portlet session attribute – so testing this method we just need to add
request.addParameter(“action”, “addUserAccount”);
request.addParameter(“_page”, “1″);
These tests generally check the existing state from the injected UserAccountService, call the processAction() method of the dispatcherPortlet, then re-check the UserAccountService to make sure the correct update has occurred.


Testing  Action to Render Method Flow

We can run an action, take the render parameters set by the action, and check that the expected render method is then called. Using the editUserAccount as an example, we can set-up the action request as per the previous test, then use the response from processAction() to set render parameters:

We can then call render(), and check both the returned view, and the userAccount service to ensure the action has completed as expected.

Testing Other Components

For mocking of service layers or external resources (such as database or web service layers) outside of a container, consider using a mocking framework such as EasyMock or Mockito.

Validation Testing

Using Spring Portlet MVC, we often have controller that processes user input from forms.  For such logic, we have validation of field data in the Model.  In my blog post on Spring MVC Validation, I discussed various ways to use validation.   Here we will discuss testing such validations.
In the controller, I have a validator wired in:

public class UserAccountController {
private UserAccountService userAccountService;
private Validator myValidator;
The Validator class looks like this
public class AddUtilityAccountValidator implements Validator {
private Validator validator;
public void setValidator(Validator validator) {
this.validator = validator;
public boolean supports(Class&amp;amp;amp;lt;!--?--&amp;amp;amp;gt; clazz) {
return clazz.equals(CreateUtilityAccountForm.class);
public void validate(Object target, Errors errors) {
validator.validate(target, errors);
CreateUtilityAccountForm form = (CreateUtilityAccountForm)target;
if (StringUtils.isBlank(form.getAccountNumber())) {
}else if (StringUtils.isNotBlank(form.getAccountNumber()) &amp;amp;amp;amp;&amp;amp;amp;amp;
!StringUtils.isNumeric(form.getAccountNumber())) {
errors.rejectValue(&amp;amp;amp;quot;accountNumber&amp;amp;amp;quot;, &amp;amp;amp;quot;NotNumeric&amp;amp;amp;quot;);
if (StringUtils.isNotBlank(form.getSsnLast4()) &amp;amp;amp;amp;&amp;amp;amp;amp;
!StringUtils.isNumeric(form.getSsnLast4())) {
errors.rejectValue(&amp;amp;amp;quot;ssnLast4&amp;amp;amp;quot;, &amp;amp;amp;quot;NotNumeric&amp;amp;amp;quot;);
if (StringUtils.isNotBlank(form.getZipCode()) &amp;amp;amp;amp;&amp;amp;amp;amp;
!StringUtils.isNumeric(form.getZipCode())) {
errors.rejectValue(&amp;amp;amp;quot;zipCode&amp;amp;amp;quot;, &amp;amp;amp;quot;NotNumeric&amp;amp;amp;quot;);
if (StringUtils.isBlank(form.getDescription())) {
errors.rejectValue(&amp;amp;amp;quot;description&amp;amp;amp;quot;, &amp;amp;amp;quot;NotEmpty&amp;amp;amp;quot;);
} else if (!StringUtils.isAlphanumericSpace(form.getDescription())) {
errors.rejectValue(&amp;amp;amp;quot;description&amp;amp;amp;quot;, &amp;amp;amp;quot;NotAlphaNumericSpace&amp;amp;amp;quot;);
For this example, a test class would be as follows below. The first two tests cover all valid and all invalid, respectively, the third covers one attribute invalid.
@ContextConfiguration(locations = &amp;amp;amp;quot;classpath:applicationContext-test.xml&amp;amp;amp;quot;)
@TestExecutionListeners(value = { DependencyInjectionTestExecutionListener.class })
public class AddUserAccountValidationTest extends AbstractJUnit4SpringContextTests {
private AddAccountValidator createAccountValidator;
public void allEntriesAreValid() {
CreateMyAccountForm member = new CreateMyAccountForm();
BindException errors = new BindException(member, &amp;amp;amp;quot;Member good&amp;amp;amp;quot;);
createAccountValidator.validate(member, errors);
Assert.assertTrue(&amp;amp;amp;quot;Errors found&amp;amp;amp;quot; + errors.getErrorCount(),
errors.getErrorCount() == 0);
public void noEntriesAreValid() {
MemberAccountModel member = new MemberAccountModel();
BindException errors = new BindException(member, &amp;amp;amp;quot;Member bad&amp;amp;amp;quot;);
Set&amp;amp;amp;gt; violations = validator
public void accountNumberNotSet() {
CreateMyAccountForm model = new CreateMyAccountForm();
// model.setAccountNumber(&amp;amp;amp;quot;12323132312&amp;amp;amp;quot;);
BindException errors = new BindException(model, &amp;amp;amp;quot;Member&amp;amp;amp;quot;);
createAccountValidator.validate(model, errors);
Assert.assertEquals(1, errors.getErrorCount());
and so forth for testing all the permutations of supported validations.


UI testing

The variety and complexity of the UI technologies that can be used with Spring MVC can make such testing difficult, though for testing the UI of a portlet when deployed to a container, consider using a web testing product such as Selenium or WebTest, as with any other web application or portal.  Such testing is outside the scope of this post, but may be discussed in a future post.


Integration or unit testing for Portlet development is as useful and important as unit testing is for any other form of development. The biggest pain point I have found is that, once unit tests have been run to ensure a controller is working correctly, it then takes time to deploy a portal application into a container (like Liferay) before the UI interaction and service integration subtleties can be discovered.  However, in a test-driven development mindset, it will always be easier and more efficient for a developer to find any errors using tests that can be run through their IDE or automated into a continuous integration build cycle (such as with tools like Bamboo or Jenkins).  Additionally, the more detailed your test cases the more maintainable your portlet code will be.  They will be essential to have for future refactoring or enhancements.


Spring Portlet MVC
Spring MVC Showcase project
Portlets in Action book blog

TAGS: Software Development, Portal, Software Solutions, Java

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Subscribe to Our Newsletter

Recent Blog Posts