Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Can't say this is the best method to do so : but to unit test a simple servlet like that (one not using forwards, context etc..) what you could simply do is : </p> <ol> <li>Create mock HttpServletReqeust and HttpServletResponse instances using any mocking library. Even simpler would be using RequestWrapper and ResponseWrapper classes (simple custom classes implemented by extending the HttpServletReqeust and HttpServletResponse classes).</li> <li>On these mock (or custom) instances set certain properties - the parameters you want to test against in each test case - e.g. <code>op=add</code> for a addition unit test. If you are using custom classes, you can simply set them in an internal properties object. If you are using mocks, then settings expectations would do.</li> <li>Create an instance of the servlet - <code>new Calculator()</code>, keeping the required libs in the class path. Now call the <code>service</code> method on this instance.</li> <li>When the call returns, get the o/p from the response class and assert it. Since the response class is again a custom class or a mocked version, this should be easy.</li> </ol> <p>For mocking, a simply starting point would be EasyMock or Mockito (my fav) </p> <p>An example for the wrapper : <a href="http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/http/HttpServletRequestWrapper.html" rel="nofollow">http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/http/HttpServletRequestWrapper.html</a></p> <p>HTH</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload