I'm using anorm for play framework and I have the following service class:
@javax.inject.Singleton
class ProductService @Inject() (dbApi: DBApi) {
private val DB = dbApi.database("default")
def save(product: Product) = {
DB.withConnection { implicit connection =>
....
}
}
}
Two issues here:
1) I do not wish to add the line private val DB = dbApi.database("default")
in each Service class. What is the best way to abstract this?
2) I would also like to have the datasource configurable so that I can pass test datasource when writing Integration tests
Test class:
import models.ProductService
import org.scalatestplus.play.{OneAppPerSuite, PlaySpec}
import play.api.db.Databases
class ProductSpec extends PlaySpec with OneAppPerSuite {
var productService: ProductService = app.injector.instanceOf(classOf[ProductService])
Databases.withDatabase(
driver = "com.mysql.jdbc.Driver",
url = "jdbc:mysql://localhost/playtest",
config = Map(
"user" -> "test",
"password" -> "demo"
)
) { database =>
import play.api.db.evolutions._
Evolutions.applyEvolutions(database)
"Product" should {
"be retrieved by Id" in {
val product = productService.get(23)
product.get.name must equal("mobile")
}
}
}
}
Any suggestions?