java - 如何知道 HttpServletResponse 重定向到哪里?

标签 java servlets testing

我正在学习软件测试,因为我主修计算机科学。教授给了我们一个用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 来测试所有方法,包括这个方法。对于这一特定方法,我想检查程序是否重定向到一个位置或另一个位置,但我不知道该怎么做。你有什么主意吗?谢谢。

最佳答案

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

关于java - 如何知道 HttpServletResponse 重定向到哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33160208/

相关文章:

java - java中的新运算符

java - 覆盖动态创建的各个 JTable 单元格的单元格编辑器

javascript - 使用 IF block 后 JSP Servlet 不工作

php - 测试设计 : How do I simulate the passage of time to test the detection of and response to events scheduled in the future?

java - 创建简单的 Spring AOP 时出现异常抛出建议演示

java - HTML 表单 Action Java

java - php 和 servlet 应用程序之间的通信

java - HttpSessionListener.sessionCreated() 未被调用

c++ - 使用 Gmock 将真实函数重新路由到模拟函数?

reactjs - 如何测试使用 enzyme 改变 useState 状态的点击事件?