//2013-01-10 johnpfeiffer
package net.kittyandbear;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import org.apache.log4j.Logger;
import org.easymock.EasyMock;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;
import org.springframework.context.support.StaticMessageSource;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
public class ServletControllerTest {
private static final Logger logger = Logger.getLogger( ServletController.class.getName() );
@Rule
public ErrorCollector errorCollector = new ErrorCollector();
private ServletController servletController;
@Before
public void setUp() throws Exception {
servletController = new ServletController();
}
@Test
public void parameter_Null_Redirects_To_Error_Page() throws Exception {
// Given:
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
final String defaultErrorTitle = "default error title";
final String defaultErrorMessage = "default error message";
StaticMessageSource fakeMessageSource = new StaticMessageSource();
fakeMessageSource.addMessage( "error.title.DEFAULT", request.getLocale(), defaultErrorTitle );
fakeMessageSource.addMessage( "error.message.DEFAULT", request.getLocale(), defaultErrorMessage );
servletController.setMessageSource( fakeMessageSource );
// When:
servletController.handleRequest( request, response );
// Then:
assertEquals( defaultErrorTitle, request.getSession().getAttribute( "errorTitle" ) );
assertEquals( defaultErrorMessage, request.getSession().getAttribute( "errorMessage" ) );
assertEquals( ServletController.VIEW_FOLDER + "/" + ServletController.JSP_ERROR, response.getForwardedUrl() );
EasyMock.verify();
}
} // end class
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
EXAMPLE SERVLET
protected static final String VIEW_FOLDER = "view";
protected static final String JSP_ERROR = "error.jsp";
public void setMessageSource( MessageSource messageSource ) { //TODO: use builder pattern to ensure this is not null!
this.messageSource = messageSource;
}
@Override
public void handleRequest( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
logger.debug( "handleRequest()" );
RequestDispatcher dispatcher = null;
if( parameter == null ) ) {
request.getSession().setAttribute( "errorTitle", this.retrieveMessage( request, "error.title.DEFAULT" ) );
request.getSession().setAttribute( "errorMessage", this.retrieveMessage( request, "error.message.DEFAULT" ) );
dispatcher = request.getRequestDispatcher( VIEW_FOLDER + "/" + JSP_ERROR );
}
dispatcher.forward( request, response );