1
//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 如u可以看到,總和變量不能被嘲笑的Cuz將打敗目的,我希望它返回在servlet調用後得到了什麼。任何人都可以幫助或提供不同的方法。嘲笑對象返回實際數據
「它在NavigationParams上返回null,因爲NavigationParams在servlet調用中設置」< - 也許是這樣,但是您不要模擬適當的方法,所以Mockito在這裏默認默認。那是什麼方法? .setAttribute(),另一個? – fge
我不明白。你在嘲笑請求,POSTing,然後想要斷言模擬請求中的屬性?你在這裏的測試用例是什麼? –
我不能設置任何東西,NavigationParams在servlet調用上設置,但我的請求對象被模擬,但我不想模擬request.getAttribute(「NavigationParams」),我想它返回實際上在servlet上計算的內容呼叫。 – Vivek