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?