2013-04-22 51 views
2

我使用基於Java的配置在Web應用程序測試spring上下文?沒有XML

@RunWith(SpringJUnit4ClassRunner.class) 
@WebAppConfiguration 
@ContextConfiguration(????????????) 
public class PersistenceConfigurationTest { 

    @PersistenceContext EntityManager entityManager; 
    @Autowired DataSource dataSource; 

    @Test 
    public void infrastructureShouldBeAutowired() { 
     assertNotNull(dataSource); 
     assertNotNull(entityManager); 
    } 
} 

附加備註: 有一些答案與建議如何基於相同的配置類創建另一個方面。我不能這樣做,因爲我微調創建的上下文(添加一些屬性)。我剛剛添加了代碼

+0

需要澄清一下,你想知道如何測試你的'SpringInitializer'類嗎?或者你想知道如何爲使用java配置的測試加載'@ ContextConfiguration'? – Akshay 2013-04-22 15:47:15

+0

不,我想測試我的道。但我正在建立我的環境手動 – piotrek 2013-04-22 15:57:17

回答

0

這篇博文應該幾乎回答你的問題(我只是希望你使用的是Spring 3.1)。

http://blog.springsource.org/2011/06/21/spring-3-1-m2-testing-with-configuration-classes-and-profiles/

滾動到集成測試與@Configuration類部分

希望能解決你的問題。

+0

我剛剛更新我的問題。在這篇文章中沒有解決方案 – piotrek 2013-04-22 16:29:29

+0

我現在不明白你的問題..你說你想單元測試,或者測試你的dao;但你也想加載整個上下文?你不應該只加載你想測試和測試的東西嗎? – Akshay 2013-04-22 16:33:27

0
@Configuration 
@ComponentScan("com.xxx.xxx") 
public class Config {} 

public class SpringInitializer implements WebApplicationInitializer { 

    public void onStartup(ServletContext servletContext) throws ServletException { 
     AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); 
     ctx.register(Config.class); 

     // Register and map the dispatcher servlet 
     ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx)); 
     dispatcher.setLoadOnStartup(1); 
     dispatcher.addMapping("/"); 
    } 

} 

@RunWith(SpringJUnit4ClassRunner.class) 
@WebAppConfiguration 
@ContextConfiguration(classes = {Config.class}) 
public class PersistenceConfigurationTest { 

    @PersistenceContext EntityManager entityManager; 
    @Autowired DataSource dataSource; 

    @Test 
    public void infrastructureShouldBeAutowired() { 
     assertNotNull(dataSource); 
     assertNotNull(entityManager); 
    } 

} 
+0

我剛剛更新我的問題(對不起,沒有更具體)。我不能使用這個解決方案,因爲它不允許我配置上下文 – piotrek 2013-04-22 16:30:24