簡體   English   中英

集成測試中的Spring autowire HttpServletRequest

[英]Spring autowire HttpServletRequest in integration tests

我們有像

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

暫時變通了,但是看起來像是正確的方法:在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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM