2014-12-06 144 views
2

由於定製框架依賴關係,我無法升級到Spring 3.2+。我被困在3.1.x上。我試圖獲得在Spring的JUnit測試的WebApplicationContext像這樣:在Spring 3.1中獲取WebApplicationContext Junit測試

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = "file:src/main/webapp/WEB-INF/spring/context.xml") 
public class WebIntegrationTest { 

    @Autowired 
    private WebApplicationContext ctx; 

這符合市場預期,不加載的WebApplicationContext。

我意識到,在Spring 3.2或更高版本中,我可以使用@WebAppConfiguration來告訴Spring我想提供一個Web上下文,但是如何通過依賴約束來實現這一點?

+1

你不能。至少不使用普通的spring類,你必須編寫自己的代碼並自己構建一個'XmlWebApplicationContext',並使用'MockServletContext'來模擬Web依賴(可能還有更多)。這將是更容易強制升級恕我直言。 – 2014-12-06 16:33:57

回答

2

我也是停留在3.1,至少要等到我能得到足夠的測試解決這個代碼升級 - 但無法測試不夠,直到我能得到一個工作的WebApplicationContext ...

這是不是太很難構建WebApplicationContext,只有一整個早上的反覆試驗。

所以,對於像

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(loader = MyLoader.class, 
    locations = 
    { 
    "file:WEB-INF/springcontexts/spring-security-common.xml", 
    "file:WEB-INF/springcontexts/webapp-common.xml" 
}) 
public class LoginIntegrationTest { 

一個測試,你可以定義

public class MyLoader implements ContextLoader { 

    @Override 
    public String[] processLocations(Class<?> clazz, String... locations) { 
     return locations; 
    } 

    @Override 
    public ApplicationContext loadContext(String... locations) throws Exception { 
     XmlWebApplicationContext result = new XmlWebApplicationContext(); 
     MockServletContext servletContext = new MockServletContext("target/webapp", new FileSystemResourceLoader()); 
     result.setServletContext(servletContext); 
     result.setServletConfig(new MockServletConfig(servletContext)); 
     result.setConfigLocations(locations); 
     result.refresh(); 
     return result; 
    } 
} 

你需要改變的路徑以符合您自己,或通過他們周圍莫名其妙。