Jojo
Jojo

Reputation: 278

Specify database in test

I want to run model tests without altering my database. I'm using a mysql database without evolutions.

Is it possible to specify a different database for my tests? Or copy the mysql schema into a memory database ?

I tried making a separate config and use it like this:

play test -Dconfig.resource=application.test.conf

without profit.

Upvotes: 0

Views: 113

Answers (1)

Sky
Sky

Reputation: 2609

you can use multiple database in play application. here i am giving example for three databases in application.(prod,dev,test)

write conf file for production (in conf directory)

prod.conf

include "application.conf"

db.default.driver=org.postgresql.Driver                                                                             
db.default.url="jdbc:postgresql://localhost:5432/productiondatabase"  
db.default.user="postgres"
db.default.password="postgres"

write conf file for develop

dev.conf

include "application.conf"

db.default.driver=org.postgresql.Driver                                                                             
db.default.url="jdbc:postgresql://localhost:5432/developmentdatabase"
db.default.user="postgres"
db.default.password="postgres"

write conf file for test

test.conf

include "application.conf"

db.default.driver=org.h2.Driver
db.default.url="jdbc:h2:mem:test"
db.default.user=sa
db.default.password=""

Now write Global.scala (in app directory)

import play.api._  
import play.api.Logger  
import com.typesafe.config.ConfigFactory   
import java.io.File 

 object Global extends GlobalSettings {    

      override def onLoadConfig(config: Configuration, path: File, classloader:     ClassLoader,mode: Mode.Mode): Configuration = {

    Logger.info("Application  configuration file is loading with " + mode.toString + "  mode")

    val modeSpecificConfig = config ++ Configuration(ConfigFactory.load(s"${mode.toString.toLowerCase}.conf"))
    super.onLoadConfig(modeSpecificConfig, path, classloader, mode)

  }
}

$ play test => it automatically connect to test database.

$ play run => it automatically connect to dev database.

$ play start =>it automatically connect to prod database.

Upvotes: 1

Related Questions