如何模拟 HttpServletRequest getParameter 解码行为?

问题描述

基于我发现的 on a few 搜索,在 GET 请求上,HttpServletRequest getParameter 将返回解码后的参数值 url。

基于此行为,我进行了一个测试,即 url 在读取参数值后对其进行编码。但是,一旦进入被测试的方法,参数就不会按预期解码。我假设这是因为我没有正确创建请求。如何创建请求以模拟解码后的行为?

到目前为止我的测试:

@RunWith(springrunner.class)
public class MyControllerTest
{
    @InjectMocks
    private MyController controller;

    private mockmvc mockmvc;

    @Before
    public void setUp()
    {
        MockitoAnnotations.initMocks(this);
        mockmvc = mockmvcBuilders.standalonesetup(controller).build();
    }

    @Test
    public void test() throws Exception
    {
        MockHttpServletRequestBuilder get = 
            mockmvcRequestBuilders.get("/myendpoint")
                .param("redirectTo","%2Fnewpath%3Fparam1%3Dval1");

        mockmvc.perform(get).andExpect(status().isOk());
    }
}

我的方法正在测试中:

@GetMapping("/myendpoint")
public ModelAndView myendpoint(HttpServletRequest request,HttpServletResponse response) throws Exception
{
    String redirectTo = request.getParameter("redirectTo");

    // expected value from decoding behavior: /newpath?param1=val1

    // but actual value from test remains unchanged: %2Fnewpath%3Fparam1%3Dval1

    ....
}

提前致谢, 亚历克斯

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)