用url字符串创建模拟httpservletrequest?

sdnqo3pr  于 2021-07-13  发布在  Java
关注(0)|答案(5)|浏览(451)

我有一个服务,它对httpservletrequest对象执行一些工作,特别是使用request.getparametermap和request.getparameter来构造一个对象。
我想知道是否有一个简单的方法来获取一个以字符串形式提供的url,比如

String url = "http://www.example.com/?param1=value1&param";

并轻松地将其转换为httpservletrequest对象,以便使用单元测试对其进行测试?或者至少让request.getparametermap和request.getparameter正常工作?

d4so4syb

d4so4syb1#

spring在其spring测试模块中有mockhttpservletrequest。
如果您使用的是maven,则可能需要向pom.xml添加适当的依赖项。你可以在mvnrepository.com上找到spring测试。

xfb7svmp

xfb7svmp2#

下面是如何使用mockhttpservletrequest:

// given
MockHttpServletRequest request = new MockHttpServletRequest();
request.setServerName("www.example.com");
request.setRequestURI("/foo");
request.setQueryString("param1=value1&param");

// when
String url = request.getRequestURL() + '?' + request.getQueryString(); // assuming there is always queryString.

// then
assertThat(url, is("http://www.example.com:80/foo?param1=value1&param"));
s5a0g9ez

s5a0g9ez3#

最简单的模仿 HttpServletRequest :
创建匿名子类:

HttpServletRequest mock = new HttpServletRequest ()
{
    private final Map<String, String[]> params = /* whatever */

    public Map<String, String[]> getParameterMap()
    {
        return params;
    }

    public String getParameter(String name)
    {
        String[] matches = params.get(name);
        if (matches == null || matches.length == 0) return null;
        return matches[0];
    }

    // TODO *many* methods to implement here
};

使用jmock、mockito或其他一些通用模拟框架:

HttpServletRequest mock = context.mock(HttpServletRequest.class); // jMock
HttpServletRequest mock2 = Mockito.mock(HttpServletRequest.class); // Mockito

使用httpunit的servletunit,不要模拟请求。

z9ju0rcb

z9ju0rcb4#

您通常会在集成测试中测试这类东西,集成测试实际上连接到一个服务。要进行单元测试,应该测试servlet的doget/dopost方法使用的对象。
一般来说,您不想在servlet方法中包含太多代码,您应该创建一个bean类来处理操作,并将您自己的对象传递给它,而不是servlet api对象。

kcugc4gi

kcugc4gi5#

对于那些寻找嘲笑方式的人 POST httpservletrequest with json payload,下面是kotlin,但是这里的关键是要模拟 request.getInputStreamHttpServletRequest ```
@Mock
private lateinit var request: HttpServletRequest

@Mock
private lateinit var response: HttpServletResponse

@Mock
private lateinit var chain: FilterChain

@InjectMocks
private lateinit var filter: ValidationFilter

@Test
fun continue filter chain with valid json payload() {
val payload = """{
"firstName":"aB",
"middleName":"asdadsa",
"lastName":"asdsada",
"dob":null,
"gender":"male"
}""".trimMargin()

whenever(request.requestURL).
    thenReturn(StringBuffer("/profile/personal-details"))
whenever(request.method).
    thenReturn("PUT")
whenever(request.inputStream).
    thenReturn(DelegatingServletInputStream(ByteArrayInputStream(payload.toByteArray())))

filter.doFilter(request, response, chain)

verify(chain).doFilter(request, response)

}

相关问题