2015-10-15 94 views
1

我參加軟件測試,因爲我主修CS。教授給了我們一個用Java編寫的程序的源代碼來測試它。我現在測試這種方法:如何知道HttpServletResponse在哪裏重定向?

public static void createPanel(HttpServletRequest req, HttpServletResponse res, HttpSession hs) throws IOException 
{ 
    String panelName = req.getParameter("panelName"); 
    String panelDescription = req.getParameter("panelDescription"); 
    int employeeID = ((EmployeeProfile)hs.getAttribute("User Profile")).EmployeeID; 
    boolean result; 

    //Let's validate our fields 
    if(panelName.equals("") || panelDescription.equals("")) 
     result = false; 
    else 
     result = DBManager.createPanel(panelName, panelDescription, employeeID); 
    b = result; 

    //We'll now display a message indicating the success of the operation to the user 
    if(result) 
     res.sendRedirect("messagePage?messageCode=Panel has been successfully created."); 
    else 
     res.sendRedirect("errorPage?errorCode=There was an error creating the panel. Please try again."); 

} 

我使用Eclipse與JUnit和mockito來測試所有的方法,包括這一個。對於這個特定的方法,我想檢查程序是否重定向到一個位置或另一個位置,但我不知道該怎麼做。你有什麼主意嗎?謝謝。

+0

[這](http://stackoverflow.com/questions/14404808/how-do-i-unit-test-httpservlet)將絕對有幫助 – sam

+1

通過模擬'HttpServletResponse',例如由Mockito創建,並檢查調用了sendRedirect參數。 –

+0

是的,我已經嘲笑HttpServletResponse和其他參數,並將它們從單元測試傳遞給此方法,但我不知道是否有任何方法來查看HttpServletResponse類內部並查看它重定向的位置 –

回答

0

實際上,你可以用和的Mockito容易ArgumentCaptor實現它:

@RunWith(MockitoJUnitRunner.class) 
public class MyTest { 

    @Mock 
    private HttpServletResponse response 

    ... 

    @Test 
    public void testCreatePanelRedirection(){ 
     ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class); 
     YourClass.createPanel(request, response, session); 
     verify(response).sendRedirect(captor.capture()); 
     assertEquals("ExpectedURL", captor.getValue()); 
    } 
}