KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > mockobjects > examples > calcserver > TestCalculatorServlet


1 package com.mockobjects.examples.calcserver;
2
3 import java.io.IOException JavaDoc;
4 import javax.servlet.ServletException JavaDoc;
5 import com.mockobjects.servlet.MockHttpServletRequest;
6 import com.mockobjects.servlet.MockHttpServletResponse;
7 import com.mockobjects.util.AssertMo;
8 import com.mockobjects.util.TestCaseMo;
9
10 public class TestCalculatorServlet extends TestCaseMo {
11     private static final Class JavaDoc THIS = TestCalculatorServlet.class;
12
13     MockHttpServletRequest myMockHttpRequest = new MockHttpServletRequest();
14     MockHttpServletResponse myMockHttpResponse = new MockHttpServletResponse();
15     CalculatorServlet myServlet = new CalculatorServlet();
16
17
18     public TestCalculatorServlet(String JavaDoc name) {
19         super(name);
20     }
21
22
23     public static void main(String JavaDoc[] args) {
24         start(new String JavaDoc[]{ THIS.getName()});
25     }
26
27
28     public void testBadParameter() throws ServletException JavaDoc, IOException JavaDoc {
29
30         myMockHttpRequest.setupAddParameter("value1", "5");
31         myMockHttpRequest.setupAddParameter("value2", "fred");
32
33
34         myMockHttpResponse.setExpectedContentType("text/plain");
35
36         myServlet.init(new MockCalculator());
37         myServlet.doGet(myMockHttpRequest, myMockHttpResponse);
38
39         myMockHttpResponse.verify();
40         AssertMo.assertIncludes("Should include result", "failed", myMockHttpResponse.getOutputStreamContents());
41     }
42
43
44     public void testSuccessfulCalculation() throws ServletException JavaDoc, IOException JavaDoc {
45         myMockHttpRequest.setupAddParameter("value1", "5");
46         myMockHttpRequest.setupAddParameter("value2", "3");
47         myMockHttpRequest.setupPathInfo("/add");
48
49         MockCalculator mockCalculator = new MockCalculator();
50         mockCalculator.setupResult(666);
51
52         myMockHttpResponse.setExpectedContentType("text/plain");
53         mockCalculator.setExpectedCalculation(5, 3, "/add");
54
55         myServlet.init(mockCalculator);
56         myServlet.doGet(myMockHttpRequest, myMockHttpResponse);
57
58         mockCalculator.verify();
59         myMockHttpResponse.verify();
60         AssertMo.assertIncludes("Should get expected result", "666", myMockHttpResponse.getOutputStreamContents());
61     }
62 }
Popular Tags