1

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

@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 解决了它)。

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

4

1 回答 1

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));
于 2013-07-15T18:01:47.107 回答