我有使用 Mongo 数据库的 play 框架应用程序 v2.2(使用 play-jongo )。我在/test 文件夹中有一些测试单元类。但是,如果我使用 test
命令运行单元类或直接从 eclipse 运行,则根本没有从 Mongo DB 中找到数据,但如果我正常运行应用程序,我可以看到数据。我已经使用了 Helpers.faceApplication()
方法,但仍然没有数据。
这是单元测试代码:
@Test
public void test1() {
Helpers.running(Helpers.fakeApplication(), new Runnable() {
@Override
public void run() {
//MyUser is the mongo entity
MyUser myUser = MyUser.findById("123");
if (myUser != null) {
Logger.info("User ID: " + myUser.id);
} else {
Logger.info("User is NULL"); //it always get here
}
}
});
}
如果我运行测试单元,myUser 始终返回 null。
我感觉 Helpers.fakeApplication 没有读取 /conf/applicaton.conf
因此它无法连接到 mongo db。
有人知道在测试单元中运行时如何将play连接到mongo db吗?
最佳答案
只是一些可能有用的信息。当您创建 fakeApplication
时,您还可以提供一个数据库进行测试:
running(fakeApplication(inMemoryDatabase("test")), new Runnable() {
public void run() {
// some assertions here
}
});
这当然会使用 H2 内存数据库。我对 Mongo 不太熟悉,但对于常规 SQL 数据库,我会尝试这样的操作:
final Map<String, String> postgres = new HashMap<String, String>();
postgres.put("db.default.driver", "org.postgresql.Driver");
postgres.put("db.default.url", "jdbc:postgresql://localhost/myDataBase");
postgres.put("db.default.user", "postgres");
postgres.put("db.default.password", "password");
running(fakeApplication(postgres), new Runnable() {
public void run() {
// some assertions here
}
});
我希望这能为您提供一些有关如何继续使用 Mongo 的线索。
关于java - 在测试模式下运行时,Play 框架中的 Mongodb 中没有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26011549/