Creating a false HttpServletRequest from url string?

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

I was wondering if there is an easy way to take the provided url as a string, say

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

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

+47
java servlets mocking
Jun 23 2018-11-11T00:
source share
4 answers

Spring has a MockHttpServletRequest in its spring -test module.

If you are using maven, you may need to add the appropriate dependency to your pom.xml . You can find spring -test at mvnrepository.com .

+29
Jun 23 2018-11-11T00:
source

The simplest ways to mock an HttpServletRequest :

  • Create an anonymous subclass:

     HttpServletRequest mock = new HttpServletRequest () { private final Map<String, String[]> params = /* whatever */ public Map<String, String[]> getParameterMap() { return params; } public String getParameter(String name) { String[] matches = params.get(name); if (matches == null || matches.length == 0) return null; return matches[0]; } // TODO *many* methods to implement here }; 
  • Use jMock , Mockito, or some other common split:

     HttpServletRequest mock = context.mock(HttpServletRequest.class); // jMock HttpServletRequest mock2 = Mockito.mock(HttpServletRequest.class); // Mockito 
  • Use HttpUnit ServletUnit and don’t scoff at the request at all.

+34
Jun 23 '11 at 14:13
source

Here's how to use the 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")); 
+22
Dec 02 '13 at 16:33
source

Usually you test these things in an integration test that actually connects to the service. To run a unit test, you must check the objects used by your doGet / doPost methods.

In general, you don’t want to have a lot of code in your servlet methods, you would like to create a bean class to handle operations and pass your own objects, not API servlet objects.

+2
Jun 23 2018-11-11T00:
source



All Articles