【问题标题】:Spring autowire HttpServletRequest in integration tests集成测试中的 Spring autowire HttpServletRequest
【发布时间】:2013-06-15 08:22:15
【问题描述】:

我们有像这样的单例控制器

@Controller
class C {
  @Autowire MyObject obj;
  public void doGet() {
    // do something with obj
  }
}

MyObject 在过滤器/拦截器中创建并放入 HttpServletRequest 属性中。然后在@Configuration中获取:

@Configuration
class Config {
  @Autowire
  @Bean @Scope("request")
  MyObject provideMyObject(HttpServletRequest req) {
      return req.getAttribute("myObj");
  }
}

在主代码中一切正常,但在测试中却不行:当我从集成测试中运行它时:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/web-application-config_test.xml")
class MyTest {
    @Autowired
    C controller;

    @Test
    void test() {
       // Here I can easily create "new MockHttpServletRequest()"
       // and set MyObject to it, but how to make Spring know about it?
       c.doGet();
    }
}

它抱怨NoSuchBeanDefinitionException: No matching bean of type [javax.servlet.http.HttpServletRequest]。 (起初,它抱怨请求范围不活跃,但我按照建议使用带有 SimpleThreadScope 的 CustomScopeConfigurer 解决了它here)。

如何让 Spring 注入知道我的 MockHttpServletRequest?还是直接MyObject?

【问题讨论】:

    标签: spring spring-mvc dependency-injection spring-mvc-test


    【解决方案1】:

    暂时解决了,但看起来是正确的方法:在 Config 中,而不是 req.getAttribute("myObj"),写

    RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
    return (MyObject) requestAttributes.getAttribute("myObj", RequestAttributes.SCOPE_REQUEST);
    

    所以它不再需要 HttpServletRequest 实例了。并填写测试:

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setAttribute("myObj", /* set up MyObject instance */)
    RequestContextHolder.setRequestAttributes(new ServletWebRequest(request));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-20
      • 1970-01-01
      • 2015-04-25
      • 1970-01-01
      • 1970-01-01
      • 2022-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多