我嘲笑一個HttpServletRequest,在servlet調用中有新的值在請求中設置,因爲使用相同的請求我們正在請求某些jsp的請求,因此request對象被用作servlet的輸入對象以及下一頁的輸出。如何使用Mockito部分模擬HttpServletRequest
我嘲笑所有輸入參數,但對於所有了request.setAttribute(),我的代碼是什麼都不做,因爲它是一個嘲弄類,說如果我有
request.setAttribute(a,"10")
System.out.println("a = " + request.getAttribute("a"));
我得到空因爲我還沒有給對於Request.getAttribute(「a」)來說任何行爲都是顯而易見的,我不能,它是我對下一頁的響應,所以解釋我需要2行爲,因此我的請求對象部分模仿,並且我無法窺探或做任何部分嘲弄到目前爲止。有任何想法嗎?
代碼:
//Testcase
Myservlet.java
public void doPost(request,response)
{
String a = request.getAttribute("a");
String b = request.getAttribute("b");
int sum = Integer.parseInt(a) + Integer.parseInt(b);
request.setAttribute("sum",sum);
//well in this example i can use sum what i calculated but in real senario i can't , i have to use request.getAttribute("sum")
insertSumIntoDB(request.getAttribute("sum"));
}
}
//testMyservlet.java
@test
public void testServlet()
{
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
when(request.getAttribute(a)).thenReturn("10");
when(request.getAttribute(b)).thenReturn("20");
new Myservlet(request,response);
}
你能告訴你的嘲諷的嘗試? – Mureinik
我改變了職位。請參閱insertSumIntoDB(request.getAttribute(「sum」))這實際上是insertSumintoDb(null),因爲我沒有給request.getAttribute(「sum」)的行爲; – Vivek