日期:2014-05-17 浏览次数:20959 次
public class TestProductSearcherServlet extends DongAnShopFixture{ private String preparedHttpReqUrl = "" ; private ServletRunner runner = null ; private ServletUnitClient unitClient = null ; private ProductSearcherServlet servlet = null ; private RequestHandler handler = null ; private MockControl handlerMockControl = null ; private List<Product> expectedProducts = null ; private Request preparedRequest = null ; private Response preparedResponse = null ; public void setUp()throws Exception{ preparedHttpReqUrl = "http://localhost/donganshop/product/searcher?request=search&pagenumber=1&pagesize=5&name="+ URLEncoder.encode("电","utf8")+"%202000&number=001%20002&tlevel=0%202" ; runner = new ServletRunner(DongAnShopFixture.getWebContentPath("WEB-INF/web-test.xml"),"/donganshop"); runner.registerServlet("/product/searcher", ProductSearcherServlet.class.getName()); unitClient = runner.newClient(); handlerMockControl = MockControl.createControl(RequestHandler.class); handler = (RequestHandler) handlerMockControl.getMock(); } public void testSearcherWithFoundResult() throws Exception{ InvocationContext iCtx = unitClient.newInvocation(preparedHttpReqUrl); servlet = (ProductSearcherServlet) iCtx.getServlet(); HttpServletRequest httpRequest = iCtx.getRequest(); httpRequest.setCharacterEncoding("utf8");//设置编码为utf8 HttpServletResponse httpResponse = iCtx.getResponse(); expectedProducts = new ArrayList<Product>(); expectedProducts.add(new Product("AMD平台电脑","002001","123456789")); Map responseContext = new HashMap(); responseContext.put("products",expectedProducts); preparedResponse = new SimpleResponse(); preparedResponse.setType(AbstractResponse.TYPE_INFO); preparedResponse.setContext(responseContext); preparedRequest = getFoundResultRequest(); handler.process(preparedRequest); handlerMockControl.setReturnValue(preparedResponse); handlerMockControl.replay(); servlet.putIntoRequestHandlers(AbstractRequest.NAME_SEARCH, handler); servlet.init(); Response realResponse = servlet.processRequest(httpRequest, httpResponse); assertEquals(AbstractResponse.TYPE_INFO,realResponse.getType()); List<Product> realProducts = (List<Product>) realResponse.getContext().get("products"); assertEquals(expectedProducts,realProducts); } private Request getFoundResultRequest(){ Request request = new SimpleRequest(); request.setName("search"); request.getContext().put("pageNumber",new Integer(1)); request.getContext().put("pageSize",new Integer(5)); Map<String,List> keywords = new HashMap<String,List>(); List<String> nameWords = new ArrayList<String>(); nameWords.add("电"); nameWords.add("2000"); List<String> numberWords = new Array