From: Vincent M. <vm...@oc...> - 2001-09-05 16:35:53
|
Hi, I have a simpe servlet with a doGet() method that simply prints a text to the output stream. I would like to know what is the correct way of writing a unit test for that method. It seems the suggested way (from the Mock Object sample and source code of MockHttpServletResponse) is to write: { SampleServlet servlet = new SampleServlet(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); servlet.doGet(request, response); String expected = "<h1>A request</h1>"; String result = response.getOutputStreamContents(); assertEquals(expected, result); } However, I don't believe this is the canonical way of writing this test. I think it would be more appropriate and consistent to write (even if longer) : { SampleServlet servlet = new SampleServlet(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); MockServletOutputStream output = new MockServletOutputStream(); output.setExpectedContent("<h1>A request</h1>"); response.setupOutputStream(output); servlet.doGet(request, response); output.verify(); } Question 1 : What do you think ? Should the example be changed ? Should the MockHttpServletResponse.getOutputStreamContents() method be removed ? Question 2 : Is it possible to automatically generate a mock of ServletOutputStream ? It would certainly not generate a setExpectedContent() method, right ? It would maybe generate a setExpectedWrite() method but that would not represent the full buffer... ServletOutputStream is an object that gets written to by the method under test, which means we need some accessors to get back the data. How can Mock Maker generate these accessors in a generic way ? Thanks -Vincent |