package com.mockobjects.examples.calcserver;

import java.io.IOException;
import javax.servlet.ServletException;
import com.mockobjects.servlet.MockHttpServletRequest;
import com.mockobjects.servlet.MockHttpServletResponse;
import com.mockobjects.util.AssertMo;
import com.mockobjects.util.TestCaseMo;

public class TestCalculatorServlet extends TestCaseMo {
    private static final Class THIS = TestCalculatorServlet.class;

    MockHttpServletRequest myMockHttpRequest = new MockHttpServletRequest();
    MockHttpServletResponse myMockHttpResponse = new MockHttpServletResponse();
    CalculatorServlet myServlet = new CalculatorServlet();


    public TestCalculatorServlet(String name) {
        super(name);
    }


    public static void main(String[] args) {
        start(new String[]{ THIS.getName()});
    }


    public void testBadParameter() throws ServletException, IOException {

        myMockHttpRequest.setupAddParameter("value1", "5");
        myMockHttpRequest.setupAddParameter("value2", "fred");


        myMockHttpResponse.setExpectedContentType("text/plain");

        myServlet.init(new MockCalculator());
        myServlet.doGet(myMockHttpRequest, myMockHttpResponse);

        myMockHttpResponse.verify();
        AssertMo.assertIncludes("Should include result", "failed", myMockHttpResponse.getOutputStreamContents());
    }


    public void testSuccessfulCalculation() throws ServletException, IOException {
        myMockHttpRequest.setupAddParameter("value1", "5");
        myMockHttpRequest.setupAddParameter("value2", "3");
        myMockHttpRequest.setupPathInfo("/add");

        MockCalculator mockCalculator = new MockCalculator();
        mockCalculator.setupResult(666);

        myMockHttpResponse.setExpectedContentType("text/plain");
        mockCalculator.setExpectedCalculation(5, 3, "/add");

        myServlet.init(mockCalculator);
        myServlet.doGet(myMockHttpRequest, myMockHttpResponse);

        mockCalculator.verify();
        myMockHttpResponse.verify();
        AssertMo.assertIncludes("Should get expected result", "666", myMockHttpResponse.getOutputStreamContents());
    }
}