在Spring-test集成测试中自动连接HttpServletRequest

时间:2015-06-10 12:56:37

标签: java spring spring-mvc spring-test mockmvc

我正在尝试进行测试以涵盖登录功能。 Spring的版本是3.2.12。我有一个会话bean,声明为:

@Service
@Scope(value = "session", proxyMode = ScopedProxyMode.INTERFACES)
public class ClientSessionServiceImpl implements ClientSessionService {
    @Autowired
    private HttpServletRequest request;
    // This method is called during the login routine from the filter
    public boolean checkUser() {
    // I rely on request attributes here, which were set in the filter
    }

这在服务器上运行时效果很好,但是当使用弹簧测试运行时,问题就出现了。这是我的测试方法:

this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).addFilter(springSecurityFilterChain).build();
mockMvc.perform(post(URL));

调试后,我发现,当测试弹簧上下文开始时,在     ServletTestExecutionListener.setUpRequestContextIfNecessary 创建了一个MockHttpServletRequest实例,     MockHttpServletRequest request = new MockHttpServletRequest(mockServletContext);     //让我们调用这个实例A. 这是随处可见的实例,我使用

@Autowired
HttpServletRequest request;

然而,调用MockMvc.perform,创建另一个MockHttpServletRequest实例(让我们称之为实例B),它被传递给所有过滤器,servlet等。所以,基本上,我在请求中的过滤器中设置的属性,无法在ClientSessionServiceImpl中读取,因为在那里注入了不同的MockHttpServletRequest实例。

我花了很多时间在这上面,但仍然没有找到解决方案。

P.S。 我通过StackOverflow搜索,有类似标题的问题,但描述了与我不同的问题,因为我不想将HttpServletRequest作为参数传递,并且宁愿让它自动装配,除非有充分的理由

4 个答案:

答案 0 :(得分:1)

  

因此,基本上,我在请求中的过滤器中设置的属性可以是&#t; t   在ClientSessionServiceImpl中读取,因为不同的实例   MockHttpServletRequest注入那里。

关于Spring RequestAttributes填充RequestContextHolder的时间问题,这是一个时间问题。在制作中,我假设您正在配置RequestContextFilterRequestContextListener

在任何情况下,在测试中手动将RequestContextFilter的实例添加到过滤器链的前面都可以解决问题。

mockMvc = MockMvcBuilders
  .webAppContextSetup(this.wac)
  .addFilters(new RequestContextFilter(), testFilterChain)
  .build();

请注意,这将成为Spring Framework 4.2中的默认行为:模拟RequestContextFilter的代码将直接在MockMvc中实现。有关详细信息,请参阅JIRA问题SPR-13217

另外,不支持配置MockHttpServletRequest创建的ServletTestExecutionListener。如果您使用MockMvc,则需要通过RequestBuilders配置模拟请求。

但是,如果你有这样的说法,如果你有一个具体的需要手动修改由ServletTestExecutionListener创建的模拟请求然后重新使用MockMvc,你可以在你的创建中创建以下类项目:

package org.springframework.test.web.servlet.request;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.http.HttpMethod;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * Patched version of {@link MockHttpServletRequestBuilder}.
 *
 * @author Sam Brannen
 * @since 4.2
 */
public class PatchedMockHttpServletRequestBuilder extends MockHttpServletRequestBuilder {

    public static MockHttpServletRequestBuilder get(String urlTemplate, Object... urlVariables) {
        return new PatchedMockHttpServletRequestBuilder(HttpMethod.GET, urlTemplate, urlVariables);
    }

    public PatchedMockHttpServletRequestBuilder(HttpMethod httpMethod, String urlTemplate, Object... urlVariables) {
        super(httpMethod, urlTemplate, urlVariables);
    }

    /**
     * Create a {@link MockHttpServletRequest}.
     * <p>If an instance of {@code MockHttpServletRequest} is available via
     * the {@link RequestAttributes} bound to the current thread in
     * {@link RequestContextHolder}, this method simply returns that instance.
     * <p>Otherwise, this method creates a new {@code MockHttpServletRequest}
     * based on the supplied {@link ServletContext}.
     * <p>Can be overridden in subclasses.
     * @see RequestContextHolder#getRequestAttributes()
     * @see ServletRequestAttributes
     */
    @Override
    protected MockHttpServletRequest createServletRequest(ServletContext servletContext) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes instanceof ServletRequestAttributes) {
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            if (request instanceof MockHttpServletRequest) {
                return (MockHttpServletRequest) request;
            }
        }

        return new MockHttpServletRequest(servletContext);
    }

}

注意:必须org.springframework.test.web.servlet.request包中;否则,它不能扩展MockHttpServletRequestBuilder这是必需的。

然后,使用get()而不是PatchedMockHttpServletRequestBuilder中的MockMvcRequestBuilders方法,一切都应该按预期工作!

显然,上面的示例重新实现 get(),但你可以自然地为post()等做同样的事情。

仅供参考:我最终可能会将上述修补后的createServletRequest()版本提交到Spring Framework 4.2.x(参见JIRA问题SPR-13211)。

此致

Sam( Spring TestContext Framework的作者

答案 1 :(得分:1)

我有一个类似的问题,我在我的休息控制器中自动装配了HttpServletRequest和HttpServletResponse

@Autowired protected HttpServletRequest httpRequest;
@Autowired protected HttpServletResponse httpResponse;

但是,当我尝试使用以下配置进行弹簧测试时,由于测试范围无法自动装配httpRequest,测试失败。

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration("classpath:spring-config-unit-test.xml")

搜索web后的解决方案我将模拟请求和响应声明为我的bean定义(单元测试)xml的第一行,如下所示。希望这能有所帮助

<bean class="org.springframework.mock.web.MockHttpServletRequest" name="httpRequest" lazy-init="false" />
<bean class="org.springframework.mock.web.MockHttpServletResponse" name="httpResponse" lazy-init="false" />

答案 2 :(得分:0)

您可以使用RequestPostProcessor来换出在执行中创建的请求。您可以在测试中添加一个util方法,例如

private static RequestPostProcessor mockedRequest(final MockHttpServletRequest mockHttpServletRequest) {
    return new RequestPostProcessor() {
        @Override
        public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
            return mockHttpServletRequest;
        }
    };
}

您可以通过with方法

添加此后处理器
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).addFilter(springSecurityFilterChain).build();
    mockMvc.perform(post(URL).with(mockedRequest(request)));

此处传递给request方法的mockedRequest,是您原始请求中包含您需要的属性

答案 3 :(得分:0)

尝试此配置:

@RunWith(SpringJUnit4ClassRunner.class)
public class MyTests extends AbstractContextControllerTests {

    @Test
    public void test() {
    }
}

AbstractContextControllerTests 是这样的:

@WebAppConfiguration
@ContextConfiguration(classes = {DispatcherConfig.class}, loader = AnnotationConfigWebContextLoader.class)
public class AbstractContextControllerTests {

    @Autowired
    protected WebApplicationContext wac;

}

DispatherConfig 是这样的:

@Configuration
@EnableWebMvc
public class DispatcherConfig extends WebMvcConfigurerAdapter {
}