2013-05-17 59 views
1

我試圖測試我的彈簧數據mongodb存儲庫,它是從MongoRepository擴展的接口,與embeddedMongoDb。像這樣的tutorial,我想創建不使用spring應用程序上下文的測試,如果我將mongoTemplate與我的存儲庫類一起使用,這是可以實現的。手動實例化Spring MongoRepository

所以有可能通過使用提供的實用方法傳遞Mongo & MongoTemplate實例來實例化MongoRepository接口實現。我認爲春季在啓動時會自動啓動。

回答

1

據我所知你不想使用xml配置來測試你的應用程序。和你的教程一樣,你的應用程序上下文在java類或xml文件中的配置也是一樣的。

本人來說我的測試中,我使用JUnit和打電話給我的xml配置是這樣的:

@RunWith(SpringJUnit4ClassRunner.class) 
    @ContextConfiguration(locations={"classpath:META-INF/spring/applicationContext-mongo.xml"}) 
    public class LicenseImplTest extends AbstractJUnit4SpringContextTests { 

     // Inject all repositories: 
     @Autowired 
     private IMyRepository myRepository; 
    } 

例如,在我的applicationContext-mongo.xml我有:

<?xml version="1.0" encoding="UTF-8" standalone="no"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:mongo="http://www.springframework.org/schema/data/mongo" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" 
    xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd   http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd   http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> 

    <bean id="applicationProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
     <property name="location" value="classpath:META-INF/spring/database.properties"></property> 
    </bean> 

    <mongo:db-factory dbname="${mongo.database}" host="${mongo.host}" id="mongoDbFactory" port="${mongo.port}" write-concern="SAFE" /> 

    <mongo:repositories base-package="fullpackage.repositories" />  

    <!-- To translate any MongoExceptions thrown in @Repository annotated classes --> 
    <context:annotation-config /> 

    <bean class="org.springframework.data.mongodb.core.MongoTemplate" id="mongoTemplate"> 
     <constructor-arg ref="mongoDbFactory" /> 
    </bean> 


</beans> 

的:

<mongo:repositories base-package="fullpackage.repositories" />  

允許spring在標註@Autowire時自動實例化您的存儲庫d被發現。

更簡單,更正確。個人而言,我更喜歡這種方法。