Question

I'm currently creation JUnit test for a play application. The problem comes when I try to use FakeApplication. I create one in JUnit test but when a test uses the fakeApplication instance, then I got this:

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

Here's my Java code in the JUnit test class:

    ...
@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);
}
    ...

Then my method to test (notice the dummy run so nothing should cause any trouble):

    ...
public void getMyProperty() {

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

}
    ...

I think the problem is a database connection issue, and of course when running play in run mode, everything is fine. If I don't use FakeApplication then it's fine also but I need it. All the database information in startFakeApplication method are coming from conf/application.conf so they're right.

What is strange is that I also have this line in the output screen when running test:

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

Did I missed something important here ? Thx

Was it helpful?

Solution

Are you passing your settings map to fakeApplication somewhere? Something like:

FakeApplication fakeApplication = fakeApplication(settings);

An alternative option is to have a separate application-test.conf file and include the following in your build.sbt file:

javaOptions in Test ++= Seq(
  "-Dconfig.file=conf/application-test.conf"
)

OTHER TIPS

My framework Acolyte provides a JDBC driver & tools, designed for such purposes (mock up, testing, ...): http://acolyte.eu.org

It's used already in some open source projects (Anorm, Youtube Vitess, ...), either in vanilla Java, or using its 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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top