它应该如何在Spring Data MongoDB中使用存储库方法构建一些测试?我想为我的测试设置测试数据库,因为我不想为此使用生产数据库。这应该是可能的,但我不知道。这是我的应用程序上下文:春季数据MongoDB:存储库的单元测试
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xmlns:neo4j="http://www.springframework.org/schema/data/neo4j"
xsi:schemaLocation=
"http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
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.0.xsd
http://www.springframework.org/schema/data/neo4j
http://www.springframework.org/schema/data/neo4j/spring-neo4j.xsd">
<!-- Default bean name is 'mongo' -->
<mongo:mongo host="${mongo.host}" port="${mongo.port}">
<mongo:options connections-per-host="8"
threads-allowed-to-block-for-connection-multiplier="4"
connect-timeout="${mongo.connect-timeout}"
max-wait-time="${mongo.max-wait-time}"
auto-connect-retry="true"
socket-keep-alive="true"
socket-timeout="${mongo.socket-timeout}"
slave-ok="true"
write-number="1"
write-timeout="0"
write-fsync="true"/>
</mongo:mongo>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongo" />
<constructor-arg name="databaseName" value="${mongo.db}" />
</bean>
<context:component-scan base-package="domain.company.group.project.data.repositories"/>
<!-- MongoDB repositories -->
<mongo:repositories base-package="domain.company.group.project.data.repositories.mongodb"/>
<!-- some other stuff -->
</beans>
而且,我们说,我有一个简单的存储库,如下所示:
public interface LocationRepository extends MongoRepository<Location, String>, LocationRepositoryCustom {
}
其中LocationRepositoryImpl是实现一定位置我所有的自定义方法的类(域对象)类。我的测试类的样子:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/test-context.xml"})
public class LocationRepositoryTest {
@Autowired
private LocationRepository locationRepository;
/* Some tests... */
}
我已经试过我的运行测试中嵌入一个MongoDB实例(如解释here),但它不工作:到测试数据库建立连接,但蒙戈模板似乎不能够被覆盖,因为所有保存方法都会将数据插入“生产”数据库。
我使用Spring 3.2.0和Spring Data Mongo 1.1.0.RELEASE。我正在使用Junit进行测试。
有什么建议吗?
预先感谢您。
嘿米格尔,感谢您的高抬头!最后,我实际上在生产/测试环境中使用了不同的上下文,而我注意到这两种环境似乎是要走的路。无论如何感谢您的回复,我一定会看看Fongo! Hasta otra ;-) – jarandaf 2013-06-04 14:53:11
我想提一下刚刚找到的这个库,它看起来简直太神奇了:https://github.com/lordofthejars/nosql-unit/ – jarandaf 2013-06-25 16:25:07
看起来非常有趣@jaranda,感谢分享! – 2013-06-26 16:44:16