1

我正在使用 MongoDB、Java、JDO 和 Maven。

我运行了一个简单的主应用程序,它存储了一些垃圾数据并从 mongodb 检索它,它看起来不错,但我想开始编写适当的单元测试。模拟实际的数据库交互对我来说似乎不是很有帮助,所以从技术上讲,我想编写功能测试来检查与数据库的完整交互。

我的单元测试是这样设置的:

static final Logger LOG = LoggerFactory.getLogger(DaoTest.class);
static final int PORT = 100001;
static Process mongod;
static PersistenceManagerFactory pmf;

// Class under test.
Dao dao;

@BeforeClass
public static void beforeAll() throws Exception {
  File mongoDir = new File(
      System.getProperty("java.io.tmpdir"),
      "mongodb-" + System.currentTimeMillis());
  mongoDir.deleteOnExit();
  mongod = Runtime.getRuntime().exec(String.format(
      "/bin/sh -c mongod --dbpath=%s --port=%d",
      mongoDir.getAbsolutePath(),
      PORT));
  LOG.info("Mongodb using {} on port {}.", mongoDir.getAbsolutePath(), PORT);
  Thread.sleep(1000);
  pmf = JDOHelper.getPersistenceManagerFactory("mongodbtest");
  LOG.info("DB connection URL: {}.", pmf.getConnectionURL());
}

@AfterClass
public static void afterAll() throws Exception {
  mongod.destroy();
}

@Before
public void setUp() throws Exception {
  dao = new Dao(pmf);
}

src/test/resources/META-INF/persistence.xml 是这样的:

<?xml version="1.0" encoding="UTF-8" ?>
<persistence ...>
  <persistence-unit name="mongodbtest">
    <properties>
      <property name="javax.jdo.PersistenceManagerFactoryClass"
          value="org.datanucleus.api.jdo.JDOPersistenceManagerFactory" />
      <property name="javax.jdo.option.ConnectionURL" value="mongodb://localhost:100001/contacts"/>
      <property name="javax.jdo.option.RetainValues" value="true"/>
      <property name="datanucleus.autoCreateSchema" value="true" />
      <property name="datanucleus.validateTables" value="false" />
      <property name="datanucleus.validateConstraints" value="false" />
      <property name="datanucleus.storeManagerType" value="mongodb" />
    </properties>
  </persistence-unit>
</persistence>

最后,我使用 mvn clean test 执行我的单元测试,仅此一项就可以工作,直到我添加一个尝试保存数据的实际测试。我收到以下错误:

Mongodb using /var/folders/00/0l550000h01000cxqpysvccm002cmm/T/mongodb-1373820849219 on port 100001.
DB connection URL: mongodb://localhost:100001/contacts.
Jul 14, 2013 12:54:10 PM com.mongodb.DBTCPConnector initDirectConnection
WARNING: Exception executing isMaster command on localhost/127.0.0.1:27017
java.io.IOException: couldn't connect to [localhost/127.0.0.1:27017] bc:java.net.ConnectException: Connection refused
    at com.mongodb.DBPort._open(DBPort.java:214)
    at com.mongodb.DBPort.go(DBPort.java:107)

...

Jul 14, 2013 12:54:10 PM com.mongodb.DBTCPConnector initDirectConnection
WARNING: Exception executing isMaster command on localhost/127.0.0.1:27017
java.io.IOException: couldn't connect to [localhost/127.0.0.1:27017] bc:java.net.ConnectException: Connection refused
    at com.mongodb.DBPort._open(DBPort.java:214)
    at com.mongodb.DBPort.go(DBPort.java:107)

...

ul 14, 2013 12:54:10 PM com.mongodb.DBPortPool gotError
WARNING: emptying DBPortPool to localhost/127.0.0.1:27017 b/c of error
java.io.IOException: couldn't connect to [localhost/127.0.0.1:27017] bc:java.net.ConnectException: Connection refused
    at com.mongodb.DBPort._open(DBPort.java:214)
    at com.mongodb.DBPort.go(DBPort.java:107)

...

Jul 14, 2013 12:54:10 PM org.datanucleus.store.valuegenerator.AbstractGenerator obtainGenerationBlock
INFO: Error encountered allocating block of IDs : can't call something : localhost/127.0.0.1:27017//localhost:100001/contacts

127.0.0.1:27017 是 mongodb 的默认设置,但我不知道为什么要使用它。我可以看到它正在从我的 persistence.xml 文件中获取配置,所以我很困惑。mongo文档说连接字符串 URL 格式是:

mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]

到目前为止,我只是通过 maven 运行它,因为这只是我到目前为止的情况,但我最终会遇到的另一个问题是如何在 Eclipse 中运行这些单元测试。我假设要在 Eclipse 中运行这些测试,必须进行字节码增强过程,但我不知道如何设置它。

我猜我不是第一个想要做这样的事情的人。有没有用 Java 编写功能性数据库测试的标准实践?我做错了吗?

4

3 回答 3

0

To answer my own question. There were three issues:

1) The connection string should have been:

mongo:/127.0.0.1/contacts

(note one less "/")

2) I needed to add mongoDir.mkdir();

3) The command to start the server should be

String command = String.format(
    "/bin/sh -c mongod --dbpath=%s --port=%d", 
    mongoDir.getAbsolutePath(), 
    PORT);
Runtime.getRuntime().exec(new String[] { "/bin/sh", "-c", command });

I actually ended up creating a JUnit4 Runner for this so I could have the same database throughout all tests and left up to the individual tests to manage the state of that database.

于 2013-07-15T07:11:56.833 回答
0

如果您想运行一个数据库实例进行测试(仅在您的 Maven 构建运行时运行),那么您可能会对我基于 fladdoodle Embedded Mongo API 编写的 Maven 插件感兴趣:

嵌入mongo-maven-插件

一个好处是该插件会自动下载 Mongo 发行版,因此人们无需在运行 Maven 构建之前安装 Mongo。迁移到不同的 Mongo 版本也很容易;您只需更改插件配置。

于 2013-07-17T21:33:26.810 回答
0

想想你的目标 I ran a simple main application that stores some junk data and retrieves it from mongodb and it looks ok, but I want to start writing proper unit tests.

如果您在团队中工作,您会发现当前源代码存在问题。如果您的另一个团队成员使用 staging db 怎么办?重现与 db 相关的错误将使您的数据无用、不一致和痛苦。

我认为@joelittlejohn 的解决方案更好。在您的项目中使用 Embedded-mongo。目前我在我的项目中使用https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo。你可以毫不犹豫地用你的 mongo 做任何事情。因为它只是在您运行 test 时发生

于 2018-07-16T07:53:24.917 回答