0
我有一個Scala的特點如下: -Junits使用嘲弄斯卡拉性狀和蛋糕圖案
trait Mytrait {
def saveData : Boolean = {
//make database calls to store
true
}
def getData : Integer = {
//get data from database
return i
}
}
現在,我已經聽說過蛋糕的模式,但我無法弄清楚如何申請蛋糕圖案的嘲諷特徵喜歡這個。
任何人都可以指出如何做到這一點?在那裏你形成「層」或者你從合適的DbConnectionFactory和你的特質「蛋糕」
trait Mytrait { this: DbConnectionFactory => // Require this trait to be mixed with a DbConnectionFactory
def saveData : Boolean = {
val connection = getConnection // Supplied by DbConnectionFactory 'layer'
//use DB connection to make database calls to store
true
}
def getData : Integer = {
val connection = getConnection // Supplied by DbConnectionFactory 'layer'
val i: Integer = ... // use DB connection to get data from database
return i
}
}
trait DbConnection
trait DbConnectionFactory {
def getConnection: DbConnection
}
// --- for prod:
class ProdDbConnection extends DbConnectionFactory {
// Set up conn to prod Db - say, an Oracle DB instance
def getConnection: DbConnection = ???
} // or interpose a connection pooling implementation over a set of these, or whatever
val myProdDbWorker = new ProdDbConnection with Mytrait
// --- for test:
class MockDbConnection extends DbConnectionFactory {
// Set up mock conn
def getConnection: DbConnection = ???
}
val myTestDbWorker = new MockDbConnection with Mytrait
: