Junit4测试搜索框public class GoodsSearchServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {} private final GoodsService gService = new GoodsService(); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String keyword = request.getParameter("keyword"); int pageNumber = 1; if(request.getParameter("pageNumber") != null) { try { pageNumber=Integer.parseInt(request.getParameter("pageNumber") ) ; } catch (Exception ignored) { } } if(pageNumber<=0) { pageNumber=1; } Page p =gService.getSearchGoodsPage(keyword,pageNumber); if(p.getTotalPage()==0) { p.setTotalPage(1); p.setPageNumber(1); } else { if(pageNumber>=p.getTotalPage()+1) { p =gService.getSearchGoodsPage(keyword,pageNumber); } } request.setAttribute("p", p); request.setAttribute("keyword", URLEncoder.encode(keyword,"utf-8")); request.getRequestDispatcher("/goods_search.jsp").forward(request, response); }
时间: 2024-01-22 14:02:12 浏览: 64
jUnit4详细教程
您可以使用Junit4编写以下测试用例来测试搜索框:
```
@RunWith(MockitoJUnitRunner.class)
public class GoodsSearchServletTest {
@Mock
HttpServletRequest request;
@Mock
HttpServletResponse response;
@Mock
RequestDispatcher dispatcher;
@Mock
GoodsService goodsService;
@InjectMocks
GoodsSearchServlet goodsSearchServlet;
@Test
public void testDoGet() throws Exception {
String keyword = "test";
int pageNumber = 1;
Page page = new Page();
page.setTotalPage(1);
page.setPageNumber(1);
when(request.getParameter("keyword")).thenReturn(keyword);
when(request.getParameter("pageNumber")).thenReturn(String.valueOf(pageNumber));
when(goodsService.getSearchGoodsPage(eq(keyword), eq(pageNumber))).thenReturn(page);
when(request.getRequestDispatcher("/goods_search.jsp")).thenReturn(dispatcher);
goodsSearchServlet.doGet(request, response);
verify(request).setAttribute("p", page);
verify(request).setAttribute("keyword", URLEncoder.encode(keyword,"utf-8"));
verify(request).getRequestDispatcher("/goods_search.jsp");
verify(dispatcher).forward(request, response);
}
}
```
在这个测试用例中,我们创建了一个`HttpServletRequest`和`HttpServletResponse`对象,并模拟了`GoodsService`对象。我们使用注释`@InjectMocks`将`GoodsService`对象注入到`GoodsSearchServlet`中,然后测试`doGet`方法。 我们设置了请求参数,模拟了`GoodsService`的调用,并验证了结果。
阅读全文