我正在尝试用embeddedMongoDb测试我的spring data mongodb存储库,它是从MongoRepository扩展而来的接口。像这个tutorial一样,我想创建不使用spring应用程序上下文的测试,如果我在我的存储库类中使用普通的mongoTemplate,这是可以实现的。
因此,是否可以使用提供的实用程序方法通过传递Mongo & MongoTemplate实例来实例化MongoRepository接口实现。我假设spring会在启动时自动执行此操作。
发布于 2013-05-21 18:56:41
据我所知,您希望在不使用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在找到注解@Autowired时自动实例化您的存储库。
更简单,更恰当。就个人而言,我更喜欢这种方法。
https://stackoverflow.com/questions/16604165
复制相似问题