如何知道HttpServletResponse重定向的位置?

时间:2015-10-15 23:30:58

标签: java servlets testing

我正在参加软件测试,因为我主修CS。教授给了我们用Java编写的程序的源代码来测试它。我现在正在测试这种方法:

    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来测试所有方法,包括这个方法。对于这个特定的方法,我想检查程序是否重定向到一个位置或另一个位置,但我不知道该怎么做。你有什么主意吗?感谢。

1 个答案:

答案 0 :(得分:3)

您可以使用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());
   }
}