Mimic an HTTPRequest and HTTPResponse object in Java
How do I mimic an HTTP开发者_如何学编程ServletRequest
and HTTPServletResponse
object. The reason is I want to test the behaviour of some servlets.
I know JUnit probably provides this functionality but I don't know how to use it (I will learn soon) and need to do this reasonably quickly.
HTTPServletRequest and HTTPServletResponse are both interfaces so they can't be instantiated. There is a HttpServletRequestWrapper
which implements HttpServletRequest but it doesn't seem to have any setParameter()
type methods and HttpServletResponse doesn't seem to have any implementing classes at all.
How can I test my code by passing a suitable HttpServletRequest
object and then checking that the received HttpServletResponse
object matches what I expect?
The fact that it's an interface makes it easier to mimic: It's mocking final classes that's tricky.
class MyHttpServletRequest implements HttpServletRequest
{
//whatever
}
class MyHttpServletResponse implements HttpServletResponse
{
//whatever
}
doGet(new MyHttpServletRequest(),
new MyHttpServletResponse())
Subclassing HttpServletRequestWrapper may be easier, but it's not necessary. I would look at overriding getParameter and getParameterMap
Create a dummy object:
class MyDummyRequest implements HTTPServletRequest{
//implement your own methods, for example:
public Map getParameterMap(){
Map myMap = new HashMap();
//put the params you need inside myMap
return myMap;
}
}
If you want to avoid creating dummy objects for test purposes you may look into one of the available mocking libraries for Java, such as Mockito.
精彩评论