弹簧自动装配的HttpServletRequest的集成测试(Spring autowire Htt

2019-09-27 04:34发布

我们有单控制器一样

@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] 。 (起初,它抱怨请求范围不活跃,但我解决它使用CustomScopeConfigurer与SimpleThreadScope的建议在这里 )。

如何让Spring注射知道我MockHttpServletRequest? 或者直接MYOBJECT?

Answer 1:

Workarounded是暂时的,但它看起来像正确的做法:在配置,而不是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));


文章来源: Spring autowire HttpServletRequest in integration tests