gpt4 book ai didi

java - 模拟对象返回实际数据

转载 作者:行者123 更新时间:2023-11-29 05:25:59 25 4
gpt4 key购买 nike

//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 编写一些类似的测试用例如您所见,不能模拟 sum 变量,因为这会破坏目的,我希望它返回在 servlet 调用后计算出的内容。任何人都可以提供帮助或提供不同的方法。

最佳答案

在这种情况下你不能使用模拟对象;模拟对象只是薄的 API 层,它们没有功能或智能。

使用模拟 Servlet API 的框架,如 mockrunnerSpring Web testing framework .

关于java - 模拟对象返回实际数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22655553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com