模拟对象返回实际数据

时间:2014-03-26 08:45:58

标签: java unit-testing java-ee servlets mockito

//MyServlet.java
public class MyServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, Exception {

         int sum = Integer.parseInt(request.getParameter("a")) + Integer.parseInt(request.getParameter("b"));

         request.setAttribute("sum",sum);
         RequestDispatcher dispatcher=request.getRequestDispatcher("/ShowSum.jsp");
         dispatcher.forward(request,response);
} 
}




  //TestServelt.java

 public class TestServelt {
  @Test
public void testSum() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);       
    HttpServletResponse response = mock(HttpServletResponse.class);
    RequestDispatcher dispatcher = mock(RequestDispatcher.class);
   when(request.getParameter(a)).thenReturn(10);
    when(request.getParameter(b).thenReturn(20);
    when(request.getRequestDispatcher(anyString())).thenReturn(dispatcher);
    MyServlet  testServlet =  new MyServlet ();
    testServlet.doPost(request, response); 

    int sum = (int)request.getAttribute("sum"); // here it's will return NULL.
   }
}

我正在尝试为servlet编写一些类似的测试用例 正如你所看到的那样,sum变量不能被模拟,因为它会破坏目的,我希望它返回在servlet调用之后得到的计算结果。任何人都可以帮助或给出不同的方法。

1 个答案:

答案 0 :(得分:3)

在这种情况下你不能使用模拟对象;模拟对象只是瘦API层,它们没有功能或智能。

使用框架模拟Servlet API,如mockrunnerSpring Web testing framework