2

我目前正在为播放应用程序创建 JUnit 测试。当我尝试使用 FakeApplication 时,问题就来了。我在 JUnit 测试中创建了一个,但是当测试使用 fakeApplication 实例时,我得到了这个:

[error] Test controllers.MyClassTest.getMyProperty failed: play.api.Configuration$$anon$1: Configuration error[Cannot connect to database [default]]

这是我在 JUnit 测试类中的 Java 代码:

    ...
@BeforeClass
public static void startFakeApplication() {
    Map<String, String> settings = new HashMap<String, String>();
    settings.put("db.default.url", "jdbc:mysql://myhost/releaseDB?characterEncoding=UTF-8");
    settings.put("db.default.driver", "com.mysql.jdbc.Driver");
    settings.put("db.default.user", "release");
    settings.put("db.default.password", "release");
    settings.put("db.default.jndiName", "DefaultDS");
    Helpers.start(fakeApplication);
}
    ...

然后我的测试方法(注意虚拟运行,所以不会造成任何麻烦):

    ...
public void getMyProperty() {

    Helpers.running (fakeApplication, new Runnable() {
        public void run() {
        }
    });

}
    ...

我认为问题是数据库连接问题,当然在运行模式下运行播放时,一切都很好。如果我不使用 FakeApplication 也可以,但我需要它。startFakeApplication 方法中的所有数据库信息都来自 conf/application.conf,所以它们是正确的。

奇怪的是,我在运行测试时在输出屏幕中也有这一行:

[info] play - datasource [jdbc:mysql://myhost/releaseDB?characterEncoding=UTF-8] bound to JNDI as DefaultDS

我在这里错过了什么重要的事情吗?谢谢

4

2 回答 2

0

我的框架 Acolyte 提供了 JDBC 驱动程序和工具,专为此类目的(模拟、测试等)而设计:http: //acolyte.eu.org

它已经在一些开源项目(Anorm,Youtube Vitess,...)中使用,无论是在 vanilla Java 中,还是在使用它的 Scala DSL。

val jdbcUrl = "jdbc:acolyte:anything-you-want?handler=my-unique-id"

val handler = handleStatement.withQueryDetection(...).
  withQueryHandler(/* which result for which query */).
  withUpdateHandler(/* which result for which update */).

// Register prepared handler with expected ID 'my-unique-id'
acolyte.Driver.register("my-unique-id", handler);

// then ...
Connection con = DriverManager.getConnection(jdbcUrl);
// ... Connection |con| is managed through |handler|
// Or pass the JDBC url to Play config
于 2015-04-02T07:58:26.397 回答
0

您是否将设置映射传递给 fakeApplication 某处?就像是:

FakeApplication fakeApplication = fakeApplication(settings);

另一种选择是拥有一个单独的application-test.conf文件并在文件中包含以下内容build.sbt

javaOptions in Test ++= Seq(
  "-Dconfig.file=conf/application-test.conf"
)
于 2014-05-07T18:58:00.887 回答