Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a mock HttpServletRequest out of a url string?

I have a service that does some work on an HttpServletRequest object, specifically using the request.getParameterMap and request.getParameter to construct an object.

I was wondering if there is a straightforward way to take a provided url, in the form of a string, say

String url = "http://www.example.com/?param1=value1&param"; 

and easily convert it to a HttpServletRequest object so that I can test it with my unit tests? Or at least just so that request.getParameterMap and request.getParameter work correctly?

like image 681
Anthony Avatar asked Jun 23 '11 14:06

Anthony


People also ask

What is MockHttpServletRequest?

public class MockHttpServletRequest extends Object implements HttpServletRequest. Mock implementation of the HttpServletRequest interface. The default, preferred Locale for the server mocked by this request is Locale. ENGLISH . This value can be changed via addPreferredLocale(java.

How is HttpServletRequest created?

In a typical Servlet container implementation if an HTTP request comes in, an HttpServletRequest is created right when the HTTP input data of the request is parsed by the Servlet container.

What is the difference between ServletRequest and HttpServletRequest?

ServletRequest provides basic setter and getter methods for requesting a Servlet, but it doesn't specify how to communicate. HttpServletRequest extends the Interface with getters for HTTP-communication (which is of course the most common way for communicating since Servlets mostly generate HTML).

How HttpServletRequest object is created?

Object of the HttpServletRequest is created by the Servlet container and, then, it is passed to the service method (doGet(), doPost(), etc.) of the Servlet. Extends the ServletRequest interface to provide request information for HTTP servlets.


1 Answers

Here it is how to use MockHttpServletRequest:

// given MockHttpServletRequest request = new MockHttpServletRequest(); request.setServerName("www.example.com"); request.setRequestURI("/foo"); request.setQueryString("param1=value1&param");  // when String url = request.getRequestURL() + '?' + request.getQueryString(); // assuming there is always queryString.  // then assertThat(url, is("http://www.example.com:80/foo?param1=value1&param")); 
like image 54
Guito Avatar answered Sep 28 '22 16:09

Guito