2013-06-18 75 views
1

我们有单控制器像弹簧自动装配的HttpServletRequest在集成测试

@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?

回答

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));