单元测试模拟一个httpservletrequest
时间: 2023-07-16 19:15:29 浏览: 95
可以使用Mockito框架来模拟一个HttpServletRequest对象,下面是一个示例代码:
```java
import static org.mockito.Mockito.*;
import javax.servlet.http.*;
import org.junit.Test;
public class MyServletTest {
@Test
public void testDoPost() throws Exception {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
when(request.getParameter("name")).thenReturn("John");
when(request.getParameter("age")).thenReturn("30");
new MyServlet().doPost(request, response);
verify(request, atLeast(1)).getParameter("name");
verify(request, atLeast(1)).getParameter("age");
verify(response, atLeast(1)).getWriter();
// add more assertions as needed
}
}
```
在上面的示例中,我们使用Mockito框架创建了一个HttpServletRequest和HttpServletResponse的模拟对象,并使用when()方法设置了模拟HttpServletRequest对象的getParameter()方法返回值。然后,我们调用了MyServlet类的doPost()方法,并使用verify()方法来验证模拟对象的方法是否被正确调用。
阅读全文