Unit Testing a Spring Controller

I have created a Spring 3.1 controller using the @MVC annotation and I was not too sure how to test it. When googling around I was introduced to the many mock helper classes that exist but I was not sure how to make it work. So I started with something simpler. Here is my unit test code for the HomeController that is created in the template from STS.

/**
 * 
 */
package com.cinq.test;

import java.util.Locale;

import org.junit.Before;
import org.junit.Test;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;

/**
 * @author mc
 *
 */
public class HomeControllerTest {

	private HomeController homeController;
	private Model model;
	private Locale locale;

	/**
	 * @throws java.lang.Exception
	 */
	@Before
	public void setUp() throws Exception {
		homeController = new HomeController();
		model = new ExtendedModelMap();
		locale = new Locale("fr", "CA");
	}

	@Test
	public void TestHomeController() {
		assert(homeController.home(locale, model).compareTo("home") == 0);
		assert(model.containsAttribute("serverTime"));
	}

}

As you can see there is not much to it. I could easily add a validation that the serverTime is not too far from the current time.

Next I have to figure out how to test a controller that is meant to answer Ajax calls.

Advertisements

Published by

m5c

Java developper that loves photography and good coffee

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s